我想使用具有以下结构的 jackson 从 JSON 字符串创建一个对象
public class A {
private int id;
private B b;
public A() {
id = 5;
b = new B(10, 20);
}
public int getId() {
return this.id;
}
public B getB() {
return b;
}
}
public class B {
private int first;
private int last;
public B(int first, int last) {
this.first = first;
this.last = last;
}
}
如果我使用以下代码进行序列化/反序列化,它会在反序列化步骤中失败 注意:我不想更改代码结构并为类 B 添加默认的空构造函数或使用 JsonProperty 注释。因为类 A 负责在内部创建 B,所以我需要某种方法来防止 Jackson 在尝试从 json 字符串反序列化类 A 时通过实例化新的 B 来覆盖类 A 的 b 属性
A a = new A();
ObjectMapper b = new ObjectMapper();
b.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
String jsonString = b.writeValueAsString(a);
// jsonString = {"id":5,"b":{}} which is desirable in serialization but it fails in deserialization with the following statement.
A readValue = b.readValue(jsonString, A.class);
最佳答案
@JsonIgnore 到您的私有(private) B 类变量。
IE:
@JsonIgnore
private B b;
关于java - 如何防止 jackson 在反序列化中实例化新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26107781/