我有一個問題。我只是使用傑克遜json的反序列化構建器模式的例子,但我總是得到一個空的json。 我使用jackson-databind版本2.8.4 我錯過了什麼嗎? 所以我的代碼如下:建設者模式json反序列化
價值類
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類
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);
}
}
不知道爲什麼這是downvoted ... – Mena
反序列化器將用於.readValue *你打電話.writeValue *這將需要一個串行器。 – NateN