我有问题。我只是用jackson json的例子反序列化构建器模式,但我总是得到一个空的json。 我使用jackson-databind版本2.8.4 我错过了什么吗? 所以我的代码如下:
价值等级
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);
}
}
答案 0 :(得分:0)
您只在x
课程中遗漏了y
和Value
的可访问权限 - ObjectMapper
需要访问这些才能序列化。
将以下内容添加到Value
类定义中:
public int getX() {
return x;
}
public int getY() {
return y;
}
在此上下文中无需额外注释。
您的JSON将打印出来:
{"x":2,"y":4}
您还可以使字段public
达到相同的结果,但这会污染正确的封装。