ObjectMapper still includes null values. I tried a lot of solutions found here, but nothing works. I cannot use json annotation, so my only solution is predefined setting of mapper, but this was not reflected. I thought this was due to caching of objectMapper. But my only modifies of mapper are made in Constructor. So caching would not be a problem
Dependencies:
Log4J2: 2.17.1
Fasterxml Jackson annotation: 2.13.2
Fasterxml Jackson databind: 2.13.2
Wildfly: 20.0.1
OpenJDK: 11.0.14.1
I have an objectMapper defined as global value which is instantiated in constructor. Then I have one method for building a JSON which accepts key and value. As value can by anything.
private final ObjectMapper jsonMapper;
public SomeConstructor() {
this.jsonMapper = new ObjectMapper();
this.jsonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
this.jsonMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
}
@Override
public void setJsonVar(String jsonVar, String jsonKey, Object values) {
// loads ObjectNode from memory if exists
ObjectNode jsonNode = getJsonVar(jsonVar);
// lazy init if ObjectNode not exists
if (jsonNode == null) {
jsonNode = jsonMapper.createObjectNode();
}
// add object
jsonNode.putPOJO(jsonKey, values);
}
Usage:
setJsonVar("var-A", "key-A", 1);
setJsonVar("var-A", "key-B", null);
print("var-a");
Expectation:
I want to avoid null values in JSON.
Expected: var-A: { "key-A":1 }
Got: var-A: { "key-A":1, "key-B":null }
Why does this happen and what can I do to work around this?
This option is applicable when serializing objects, custom objects or a Map
for example, but not when working with json tree. Consider this Foo
class:
public class Foo {
private String id;
private String name;
//getters and setters
}
The option to exclude nulls will work as expected with it.
Main method to illustrate it:
public class Main {
public static void main(String[] args) throws Exception {
serializeNulls();
System.out.println();
doNotSerializeNulls();
}
private static void serializeNulls() throws Exception {
ObjectMapper jsonMapper = new ObjectMapper();
Foo foo = new Foo();
foo.setId("id");
System.out.println("Serialize nulls");
System.out.println(jsonMapper.writeValueAsString(foo));
Map<String, Object> map = new LinkedHashMap<>();
map.put("key1", "val1");
map.put("key2", null);
System.out.println(jsonMapper.writeValueAsString(map));
}
private static void doNotSerializeNulls() throws Exception {
ObjectMapper jsonMapper = new ObjectMapper();
jsonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
jsonMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
Foo foo = new Foo();
foo.setId("id");
System.out.println("Do not serialize nulls");
System.out.println(jsonMapper.writeValueAsString(foo));
Map<String, Object> map = new LinkedHashMap<>();
map.put("key1", "val1");
map.put("key2", null);
System.out.println(jsonMapper.writeValueAsString(map));
}
}