如何防止 Map 中的空值和 bean 中的空字段通过 Jackson 序列化 [英] How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

查看:11
本文介绍了如何防止 Map 中的空值和 bean 中的空字段通过 Jackson 序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MapfoosMap 我想通过 Jackson 序列化.现在我想在序列化过程中进行以下两个设置:

I have a a Map<String,Foo> foosMap that I want to serialize through Jackson . Now I want following two settings on the serialization process:

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

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

What is the best way to achieve this ? I am using jackson-core1.9 and jackson-mapper1.9 jars in my project.

推荐答案

如果改变要序列化的原始 Map 数据结构以更好地表示想要序列化的实际值是合理的,那可能是一种体面的方法,这可能会减少所需的 Jackson 配置量.例如,如果可能,在调用 Jackson 之前删除 null 键条目.话说……

If it's reasonable to alter the original Map data structure to be serialized to better represent the actual value wanted to be serialized, that's probably a decent approach, which would possibly reduce the amount of Jackson configuration necessary. For example, just remove the null key entries, if possible, before calling Jackson. That said...

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

To suppress serializing Map entries with null values:

在 Jackson 2.9 之前

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

you can still make use of WRITE_NULL_MAP_VALUES, but note that it's moved to SerializationFeature:

mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

自 Jackson 2.9 以来

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

The WRITE_NULL_MAP_VALUES is deprecated, you can use the below equivalent:

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

<小时>

要抑制带有空值的序列化属性,您可以直接配置ObjectMapper,或者使用@JsonInclude 注释:

mapper.setSerializationInclusion(Include.NON_NULL);

或:

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

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

<小时>

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


To handle null Map keys, some custom serialization is necessary, as best I understand.

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

A simple approach to serialize null keys as empty strings (including complete examples of the two previously mentioned configurations):

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 条目,需要进一步的自定义序列化处理.

To suppress serializing Map entries with null keys, further custom serialization processing would be necessary.

这篇关于如何防止 Map 中的空值和 bean 中的空字段通过 Jackson 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆