【问题标题】:How to prevent jackson instantiating new object in deserialization如何防止杰克逊在反序列化中实例化新对象
【发布时间】:2014-11-24 07:28:11
【问题描述】:

我想使用以下结构的杰克逊从 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 我需要某种方法来防止杰克逊在尝试从 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);

【问题讨论】:

    标签: java json serialization jackson


    【解决方案1】:

    @JsonIgnore 到你的私有 B 类变量。

    IE:

    @JsonIgnore
    private B b;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-15
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多