杰克逊的ObjectMapper需要序列化一个值,而不是reture为null,但是不同的对象,有不同的表示形式

时间:2018-07-28 04:59:56

标签: java jackson objectmapper

我的杰克逊版本是2.9.3 有代码

public static void main(String[] args) throws IOException{

    //init objectMapper
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    //construct map
    Map<String, Object> map = Maps.newHashMap();
    map.put("boolean", "true");
    map.put("number", "123");
    map.put("string", null);
    Map<String, String> map1 = Maps.newHashMap();
    map1.put("a", null);
    map1.put("c", "d");
    map1.put("e", null);
    map.put("object", map1);
    Integer[] a = new Integer[]{null, 2, 3};
    map.put("array", a);

    //construct jsonNode;
    String test = "{\"array\":[null,2,3],\"boolean\":true,\"number\":123,\"object\":{\"a\":null,\"c\":\"d\",\"e\":null},\"string\":null}";
    JsonNode jsonNode = objectMapper.readTree(test);

    //output
    System.out.println(objectMapper.writeValueAsString(jsonNode));
    System.out.println(objectMapper.writeValueAsString(map));
}

结果是

{"array":[null,2,3],"boolean":true,"number":123,"object":{"a":null,"c":"d","e":null},"string":null}
{"number":"123","boolean":"true","array":[null,2,3],"object":{"c":"d"}}

对于Map类型,没有null,但是对于JsonNode,有null。

会发生什么?

0 个答案:

没有答案