我有一个问题。我只是使用了jackson json的例子来反序列化构建器模式,但我总是得到一个空的json。我使用的是jackson-databind 2.8.4版本我错过什么了吗?所以我的代码如下:
Value类
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;
}
}
ValueBuilder类
import com.fasterxml.jackson.annotation.JsonCreator;
//@JsonPOJOBuilder(buildMethodName = "build", withPrefix = "with")
public class ValueBuilder {
private int x;
private int 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;
}
@JsonCreator
public Value build() {
return new Value(x, y);
}
}
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);
}
}
您的Value
类中只缺少x
和y
的可访问getter - ObjectMapper
需要访问这些以便序列化。
将以下内容添加到Value
类定义中:
public int getX() {
return x;
}
public int getY() {
return y;
}
在此上下文中不需要额外的注释。
你的JSON将打印如下:
{"x":2,"y":4}
您也可以使字段public
达到相同的结果,但这会破坏正确的封装。