Requirements :
- Would like to use Builder pattern
- Jackson for deserialization
- Would not like to use setters
I am sure that jackson work based on getters and setters on the POJO. Since, I have buildder pattern, there is no point of having setters again. In this case, How can we indicate jackson to deserialize with help of Builder pattern ?
Any help would be appreciated. I tried @JsonDeserialize(builder = MyBuilder.class) and is not working.
This is required in REST jersey. I am currently jersey-media-jackson maven module for jackson marshaling and unmarshaling.
@JsonDeserialize
is the way to go, provided that you have jackson-databind
on your classpath. The following snippets are copied from the Jackson Documentation:
@JsonDeserialize(builder=ValueBuilder.class)
public class Value {
private final int x, y;
protected Value(int x, int y) {
this.x = x;
this.y = y;
}
}
public class ValueBuilder {
private int x, y;
// can use @JsonCreator to use non-default ctor, inject values etc
public ValueBuilder() { }
// if name is "withXxx", works as is: otherwise use @JsonProperty("x") or @JsonSetter("x")!
public ValueBuilder withX(int x) {
this.x = x;
return this; // or, construct new instance, return that
}
public ValueBuilder withY(int y) {
this.y = y;
return this;
}
public Value build() {
return new Value(x, y);
}
}
alternatively, use the @JsonPOJOBuilder
if you do not like method names that have the with
prefix:
@JsonPOJOBuilder(buildMethodName="create", withPrefix="con")
public class ValueBuilder {
private int x, y;
public ValueBuilder conX(int x) {
this.x = x;
return this; // or, construct new instance, return that
}
public ValueBuilder conY(int y) {
this.y = y;
return this;
}
public Value create() { return new Value(x, y); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With