Neo
Neo

Reputation: 4880

Jackson serialization with including null values for Map

I've the following POJOs that I want to serialize using Jackson 2.9.x

static class MyData {
  public Map<String, MyInnerData> members;
}
static class MyInnerData {
  public Object parameters;
  public boolean isPresent;
}

Now if I populate the data with the following sample code as shown:

Map<String, Object> nodeMap = new LinkedHashMap<>();
nodeMap.put("key-one", "val1");
nodeMap.put("key-null", null);
nodeMap.put("key-two", "val2");
Map<String, Object> child1 = new LinkedHashMap<>();
child1.put("c1", "v1");child1.put("c2", null);
nodeMap.put("list", child1);

MyInnerData innerData1 = new MyInnerData();
innerData1.parameters = nodeMap;
innerData1.isPresent = true;
MyData myData = new MyData();
myData.members = new LinkedHashMap<>();
myData.members.put("data1", innerData1);

// serialize the data
ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
String actual = mapper.writeValueAsString(myData);
System.out.println(actual);

This ends up printing

{"members":{"data1":{"parameters":{"key-one":"val1","key-two":"val2","list":{"c1":"v1"}},"isPresent":true}}}

Desired Output (same code gives correct output with Jackson 2.8.x )

{"members":{"data1":{"parameters":{"key-one":"val1","key-null":null,"key-two":"val2","list":{"c1":"v1","c2":null}},"isPresent":true}}}

If I remove the setSerializationInclusion(JsonInclude.Include.NON_NULL) on the mapper, I get the required output but the existing configuration for the ObjectMapper cant be changed. I can make changes to the POJO however.

What would be the least change to get the desired output?

Upvotes: 7

Views: 12245

Answers (1)

juliccr
juliccr

Reputation: 361

You need to configure your object like this: mapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS);

Upvotes: 15

Related Questions