为了账号安全,请及时绑定邮箱和手机立即绑定

使用 jackson 转换时 POJO 具有空值

使用 jackson 转换时 POJO 具有空值

湖上湖 2022-11-30 11:24:54
我试图寻找这个问题的答案,但意识到有多个相似但没有一个与这个匹配。我有一个具有这种结构的 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我不知道会出什么问题,因为没有返回任何异常,知道吗?
查看完整描述

2 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

您需要使用根属性model,


您可以重命名MyObject并MyModel创建一个MyObject


@JsonInclude(value = JsonInclude.Include.NON_NULL)

@JsonIgnoreProperties(ignoreUnknown = true)

public class MyObject{

    @JsonProperty("model")

    MyModel model;

}

然后检查model


查看完整回答
反对 回复 2022-11-30
?
GCT1015

TA贡献1827条经验 获得超4个赞

实际上,您需要 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);


查看完整回答
反对 回复 2022-11-30
  • 2 回答
  • 0 关注
  • 140 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号