构建器模式 json 反序列化
builder pattern json deserialize
我有问题。我刚刚使用 jackson json 的示例来反序列化构建器模式,但我总是得到一个空的 json。
我使用 jackson-databind 版本 2.8.4
我错过了什么吗?
所以我的代码如下:
价值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;
}
}
价值创造者Class
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);
}
}
开始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
class 中只缺少 x
和 y
的可访问吸气剂 - ObjectMapper
需要访问这些吸气剂才能连载。
将以下内容添加到您的 Value
class 定义中:
public int getX() {
return x;
}
public int getY() {
return y;
}
在此上下文中不需要额外的注释。
您的 JSON 将打印如下:
{"x":2,"y":4}
您也可以使字段 public
达到相同的结果,但这会破坏适当的封装。
我有问题。我刚刚使用 jackson json 的示例来反序列化构建器模式,但我总是得到一个空的 json。 我使用 jackson-databind 版本 2.8.4 我错过了什么吗? 所以我的代码如下:
价值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;
}
}
价值创造者Class
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);
}
}
开始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
class 中只缺少 x
和 y
的可访问吸气剂 - ObjectMapper
需要访问这些吸气剂才能连载。
将以下内容添加到您的 Value
class 定义中:
public int getX() {
return x;
}
public int getY() {
return y;
}
在此上下文中不需要额外的注释。
您的 JSON 将打印如下:
{"x":2,"y":4}
您也可以使字段 public
达到相同的结果,但这会破坏适当的封装。