Java 如何防止jackson在反序列化中实例化新对象

Java 如何防止jackson在反序列化中实例化新对象,java,json,serialization,jackson,Java,Json,Serialization,Jackson,我想使用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;

我想使用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到您的私有B类变量

即:

@JsonIgnore
private B b;