I am trying to deserialize a json context using Jackson 2.6.3. I have null literal in json content as below. I am trying to avoid that being added to the deserialized collection. See the output below. I tried various configuration options on the mapper. However I am unable to avoid null object in the collection. Any pointers to resolve the issue welcome.
I have seen many similar questions in stackoverflow like the one below, but all of them related to custom deserializing individual attributes in a class, but not an element in a collection.
How to deserialize JSON null to a NullNode instead of Java null?
JSON Content (Data.txt)
{
"myList": [
{
"type": "1"
},
{
"type": "2"
},
null
]
}
RootObject.java
@JsonInclude(Include.NON_NULL)
public class RootObject {
private List<Types> myList;
public List<Types> getMyList() {
return myList;
}
public void setMyList(List<Types> myList) {
this.myList = myList;
}
public String toString(){
return new ReflectionToStringBuilder(this).toString();
}
}
Types.java
@JsonInclude(Include.NON_NULL)
public class Types {
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toString(){
return new ReflectionToStringBuilder(this).toString();
}
}
JacksonTester
public class JacksonTester2 {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().withSerializationInclusion(Include.NON_EMPTY);
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
RootObject rootObject = null;
try {
rootObject = mapper.readValue(new File("Data.txt"), RootObject.class);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(rootObject);
}
}
Output
RootObject@1a74681a[myList=[Types@ace10d9[type=1], Types@5eb41c19[type=2], null]]