java - Jackson Databind 中是否有任何替代品来替代已弃用的属性 SerializationFeature.WRITE_NULL_MAP_VALUES ?

标签 java jackson deprecated jackson-databind

我们正在使用 ObjectMapper 来忽略项目中空映射的序列化

configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)

但是在 Jackson-Databind 2.9 之后,该属性已贬值,我们正在寻找替代选项。

下面的代码可以替代删除上述属性吗 -

setSerializationInclusion(Include.NON_NULL)

最佳答案

来自documentation :

Deprecated. Since 2.9 there are better mechanism for specifying filtering; specifically using JsonInclude or configuration overrides (see ObjectMapper.configOverride(Class)). Feature that determines whether Map entries with null values are to be serialized (true) or not (false).
NOTE: unlike other SerializationFeatures, this feature cannot be dynamically changed on per-call basis, because its effect is considered during construction of serializers and property handlers.

Feature is enabled by default.

简单的例子:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Value;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.HashMap;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("string", "value");
        map.put("int", 1);
        map.put("null1", null);
        map.put(null, null);

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.configOverride(Map.class).setInclude(Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL));

        System.out.println(mapper.writeValueAsString(map));
    }
}

上面的代码打印:

{
  "string" : "value",
  "int" : 1
}

关于java - Jackson Databind 中是否有任何替代品来替代已弃用的属性 SerializationFeature.WRITE_NULL_MAP_VALUES ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59136341/

相关文章:

java - Android - 将字符串日期转换为前时间日期格式

java - Jackson 自定义反序列化器,用于具有多态类型的一个字段

java - 如何使用 jackson objectmapper 反序列化

visual-studio-2017 - 如何在 Visual Studio C++17 中恢复 auto_ptr

Android Studio 项目中的 Gradle 弃用 "Relying on packaging to define the extension of the main artifact..."可以修复吗?

java - 如何确定已弃用的权限?

android - 在android中获取mp3持续时间

Java:如何从正则表达式解析 double

java - 在循环中使用 Realm 或插入列表 Android

java - Jackson:用于反序列化内部集合的对象映射器注释