Jackson Databind 中已弃用的 属性 SerializationFeature.WRITE_NULL_MAP_VALUES 是否有任何替代品?
Is there any replacement for deprecated property SerializationFeature.WRITE_NULL_MAP_VALUES in Jackson Databind?
我们正在使用 ObjectMapper 来忽略我们项目中空映射的序列化
configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
但在 Jackson-Databind 2.9 之后,属性 已贬值,我们正在寻找替代方案。
下面的代码可以替代删除上面的 属性 -
setSerializationInclusion(Include.NON_NULL)
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).
简单示例:
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
}
我们正在使用 ObjectMapper 来忽略我们项目中空映射的序列化
configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
但在 Jackson-Databind 2.9 之后,属性 已贬值,我们正在寻找替代方案。
下面的代码可以替代删除上面的 属性 -
setSerializationInclusion(Include.NON_NULL)
Deprecated. Since 2.9 there are better mechanism for specifying filtering; specifically using
JsonInclude
or configuration overrides (seeObjectMapper.configOverride(Class)
). Feature that determines whetherMap
entries with null values are to be serialized (true) or not (false).
简单示例:
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
}