Requirements :
- Would like to use Builder pattern
- Jackson for deserialization
- Would not like to use setters
我确信 jackson 是基于 POJO 上的 getter 和 setter 工作的。因为,我有 builder 模式,所以没有必要再有二传手了。在这种情况下,我们如何指示 jackson 在 Builder 模式的帮助下进行反序列化?
如有任何帮助,我们将不胜感激。我试过 @JsonDeserialize(builder = MyBuilder.class) 但没有用。
这在 REST jersey 中是必需的。我目前是用于 jackson 编码和解码的 jersey-media-jackson maven 模块。
最佳答案
@JsonDeserialize
是要走的路,前提是您的类路径上有 jackson-databind
。以下片段摘自 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);
}
}
或者,如果您不喜欢具有 with
前缀的方法名称,请使用 @JsonPOJOBuilder
:
@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); }
}
关于java - 用于反序列化的 Jackson 构建器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27409808/