java - builder pattern json deserialize -
i have problem. used example of jackson json deserializing builder pattern empty json. use jackson-databind version 2.8.4 missing something? code follows:
the value class
import com.fasterxml.jackson.databind.annotation.jsondeserialize; @jsondeserialize(builder=valuebuilder.class) public class value { private final int x, y; protected value(int x, int y) { this.x = x; this.y = y; } }
the valuebuilder class
import com.fasterxml.jackson.annotation.jsoncreator; //@jsonpojobuilder(buildmethodname = "build", withprefix = "with") public class valuebuilder { private int x; private int y; // can use @jsoncreator use non-default ctor, inject values etc public valuebuilder() { } // if name "withxxx", works is: otherwise use @jsonproperty("x") or @jsonsetter("x")! public valuebuilder withx(int x) { this.x = x; return this; // or, construct new instance, return } public valuebuilder withy(int y) { this.y = y; return this; } @jsoncreator public value build() { return new value(x, y); } }
the start class
public class start { public static void main(string[] args) throws ioexception { value newvalue = new valuebuilder().withx(2).withy(4).build(); objectmapper mapper = new objectmapper(); string jsonstring = mapper.writevalueasstring(newvalue); system.out.println(jsonstring); } }
you're missing accessible getters x
, y
in value
class - objectmapper
requires access in order serialize.
add following value
class definition:
public int getx() { return x; } public int gety() { return y; }
no need additional annotations in context.
your json print out like:
{"x":2,"y":4}
you make fields public
reach same result, defile proper encapsulation.
Comments
Post a Comment