ObjectMapper setSerializationInclusion(JsonInclude.Include.NON_NULL) 设置未反映

ObjectMapper setSerializationInclusion(JsonInclude.Include.NON_NULL) setting is not reflected

ObjectMapper 仍然包含空值。我尝试了很多在这里找到的解决方案,但没有任何效果。我不能使用 json 注释,所以我唯一的解决方案是映射器的预定义设置,但这没有反映出来。我认为这是由于 objectMapper 的缓存。但是我对映射器的唯一修改是在构造函数中进行的。所以缓存不会有问题

依赖关系:

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

我有一个 objectMapper 定义为在构造函数中实例化的全局值。然后我有一种构建接受键和值的 JSON 的方法。任何东西都可以作为价值。

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);
}

用法:

setJsonVar("var-A", "key-A", 1);
setJsonVar("var-A", "key-B", null);
print("var-a");

期望:

我想避免 JSON 中的空值。

预计:var-A: { "key-A":1 } 得到:var-A: { "key-A":1, "key-B":null }

为什么会发生这种情况,我该怎么做才能解决这个问题?

此选项适用于序列化对象、自定义对象或 Map,但 不适用于 json 树。考虑这个 Foo class:

public class Foo {

    private String id;
    private String name;

    //getters and setters
}

排除空值的选项将按预期工作。

主要方法说明一下:

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));
    }
}