简体   繁体   中英

POJO have null values when converting with jackson

I have tried to look for an answer on this but realized there are multiple similar but none matches this one.

I have a JSON object with this structure

{
  "model": {
     "serie" : "123456",
      "id" : "abc123"
    /// many fields
  },
  "externalModel": {
    "serie" : "123456",
    "fieldX" : "abcde"
   // many fields as well
}

and I'm doing this at my code:

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

where MyObject has this form:

@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)

public class MyObject {


    @JsonProperty("serie")
    String serie;

    @JsonProperty("id")
    Long id;

    MyObject() {}
   }

When I convert I don't get any exception, but rather I get myObject with all values set to null

I have no idea what could be wrong since no exception returned, any idea?

You need to use root property model ,

You can rename MyObject to MyModel and create a MyObject

@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject{
    @JsonProperty("model")
    MyModel model;
}

and then check model

Actually, you need two objects in 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  
}

Now when you use it like below, it will work fine.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM