【问题标题】:How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson如何防止 Map 中的 null 值和 bean 中的 null 字段通过 Jackson 序列化
【发布时间】:2012-07-12 01:09:44
【问题描述】:

我有一个 Map<String,Foo> foosMap 我想通过 Jackson 序列化。现在我想在序列化过程中进行以下两个设置:

  1. Map 可以有很多空值和空键,我不希望空值被序列化。
  2. 对于所有正在序列化的 Foo,我不想序列化 Foo 中引用的空对象。

实现这一目标的最佳方法是什么?我在我的项目中使用 jackson-core1.9 和 jackson-mapper1.9 jars。

【问题讨论】:

标签: java json jackson


【解决方案1】:

如果更改要序列化的原始Map 数据结构以更好地表示要序列化的实际值是合理的,那可能是一种不错的方法,这可能会减少必要的 Jackson 配置量。例如,如果可能,请在调用 Jackson 之前删除 null 键条目。那就是……


要禁止序列化具有空值的 Map 条目:

在杰克逊 2.9 之前

您仍然可以使用WRITE_NULL_MAP_VALUES,但请注意它已移至SerializationFeature

mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

自杰克逊 2.9 以来

WRITE_NULL_MAP_VALUES 已弃用,您可以使用以下等效项:

mapper.setDefaultPropertyInclusion(
   JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))

要禁止序列化具有空值的属性,您可以configure the ObjectMapper directly,或使用@JsonInclude 注释:

mapper.setSerializationInclusion(Include.NON_NULL);

或:

@JsonInclude(Include.NON_NULL)
class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

据我所知,要处理空的 Map 键,一些自定义序列化是必要的。

null 键序列化为空字符串的简单方法(包括前面提到的两个配置的完整示例):

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    Map<String, Foo> foos = new HashMap<String, Foo>();
    foos.put("foo1", new Foo("foo1"));
    foos.put("foo2", new Foo(null));
    foos.put("foo3", null);
    foos.put(null, new Foo("foo4"));

    // System.out.println(new ObjectMapper().writeValueAsString(foos));
    // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer());
    System.out.println(mapper.writeValueAsString(foos));
    // output: 
    // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}}
  }
}

class MyNullKeySerializer extends JsonSerializer<Object>
{
  @Override
  public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) 
      throws IOException, JsonProcessingException
  {
    jsonGenerator.writeFieldName("");
  }
}

class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

要禁止使用 null 键序列化 Map 条目,需要进一步的自定义序列化处理。

【讨论】:

  • 请注意,这些方向是 Jackson 2.0 特定的(com.fasterxml vs org.codehaus)。
  • @ProgrammerBruce - 是否可以防止对象映射器中特定类的空字段序列化? eg:使用相同的对象映射器序列化A类和B类,但只忽略B类中的空字段。
  • @ProgrammerBurce - 由于 jackson 已升级到 2.9,因此不推荐使用 WRITE_NULL_MAP_VALUES。你知道有没有其他方法可以做到这一点?
  • 我发现 WRITE_NULL_MAP_VALUES 从 2.9 开始等效:mapper.setDefaultPropertyInclusion(JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))
  • @AidenZhao - 我有杰克逊 2.9.2。我的 IDE,Intellij IDEA 没有为 com.fasterxml.jackson.databind.ObjectMapper 显示任何名为“setDefaultPropertyInclusion”的方法。我错过了什么吗?
【解决方案2】:

我的解决方案,希望对您有所帮助
自定义 ObjectMapper 和配置到 spring xml(注册消息转换器)

public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
    disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
    setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}

}

【讨论】:

    【解决方案3】:

    对于 Jackson 版本

    @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
    

    【讨论】:

    • 仅供参考,已弃用,上面接受的答案有最新注释:@JsonInclude(Include.NON_NULL)
    • 请注意,如果您使用的是 Jackson 1.9.x,则 JsonInclude 注释不可用,在这种情况下,您必须使用 JsonSerialize 注释。
    • 我与 Jackson 1.9.x 确认 @JsonInclude(Include.NON_NULL) 不起作用。我正在导入这个包:org.codehaus.jackson.map
    【解决方案4】:

    答案似乎有点老了,我所做的是使用这个映射器来转换一个MAP

          ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);
    

    一个简单的Map:

              Map<String, Object> user = new HashMap<String,Object>();
                user.put( "id",  teklif.getAccount().getId() );
                user.put( "fname", teklif.getAccount().getFname());
                user.put( "lname", teklif.getAccount().getLname());
                user.put( "email", teklif.getAccount().getEmail());
                user.put( "test", null);
    

    例如这样使用它:

          String json = mapper.writeValueAsString(user);
    

    【讨论】:

    • 请添加json的输出。
    猜你喜欢
    • 1970-01-01
    • 2019-04-11
    • 2014-10-29
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多