使用 jackson 转换时 POJO 具有空值

我试图寻找这个问题的答案,但意识到有多个相似但没有一个与这个匹配。


我有一个具有这种结构的 JSON 对象


{

  "model": {

     "serie" : "123456",

      "id" : "abc123"

    /// many fields

  },

  "externalModel": {

    "serie" : "123456",

    "fieldX" : "abcde"

   // many fields as well

}

我在我的代码中这样做:


 ObjectMapper mapper = new ObjectMapper();

 MyObject object = mapper.readValue(hit.getSourceAsString(), MyObject.class);

其中 MyObject 具有以下形式:


@JsonInclude(value = JsonInclude.Include.NON_NULL)

@JsonIgnoreProperties(ignoreUnknown = true)


public class MyObject {



    @JsonProperty("serie")

    String serie;


    @JsonProperty("id")

    Long id;


    MyObject() {}

   }

当我转换时,我没有得到任何异常,而是我得到了所有值都设置为null的 myObject


我不知道会出什么问题,因为没有返回任何异常,知道吗?


湖上湖
浏览 142回答 2
2回答

皈依舞

您需要使用根属性model,您可以重命名MyObject并MyModel创建一个MyObject@JsonInclude(value = JsonInclude.Include.NON_NULL)@JsonIgnoreProperties(ignoreUnknown = true)public class MyObject{    @JsonProperty("model")    MyModel model;}然后检查model

GCT1015

实际上,您需要 MyObject 中的两个对象。@JsonInclude(value = JsonInclude.Include.NON_NULL)@JsonIgnoreProperties(ignoreUnknown = true)public class MyModel {    @JsonProperty("id")    private String id;    @JsonProperty("serie")    private String serie;   //Generate getters and setters of these two}@JsonInclude(value = JsonInclude.Include.NON_NULL)@JsonIgnoreProperties(ignoreUnknown = true)public class ExternalObject {    @JsonProperty("serie")    private String serie;    @JsonProperty("fieldX")    private String fieldX;   //Generate getters and setters of these two}@JsonInclude(value = JsonInclude.Include.NON_NULL)@JsonIgnoreProperties(ignoreUnknown = true)public class MyObject{    @JsonProperty("model")    private MyModel model;    @JsonProperty("externalModel")    private ExternalObject externalModel;   //Generate getters and setters of these two  }现在,当您像下面那样使用它时,它会正常工作。ObjectMapper mapper = new ObjectMapper();MyObject object = mapper.readValue(hit.getSourceAsString(), MyObject.class);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java