你如何覆盖 Jackson 2.0 中的空序列化器? [英] How do you override the null serializer in Jackson 2.0?

查看:19
本文介绍了你如何覆盖 Jackson 2.0 中的空序列化器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jackson 进行 JSON 序列化,并且我想覆盖 null 序列化器——特别是,以便将 null 值序列化为 JSON 中的空字符串,而不是字符串null".

I'm using Jackson for JSON serialization, and I would like to override the null serializer -- specifically, so that null values are serialized as empty strings in JSON rather than the string "null".

我找到的关于如何设置空序列化程序的所有文档和示例都参考了 Jackson 1.x——例如,http://wiki.fasterxml.com/JacksonHowToCustomSerializers 不再使用 Jackson 2.0 编译,因为库中不再存在 StdSerializerProvider.该网页描述了 Jackson 2.0 的模块接口,但模块接口没有明显的方法来覆盖空序列化器.

All of the documentation and examples I've found on how to set null serializers refers to Jackson 1.x -- for example, the code at the bottom of http://wiki.fasterxml.com/JacksonHowToCustomSerializers no longer compiles with Jackson 2.0 because StdSerializerProvider no longer exists in the library. That web page describes Jackson 2.0's module interface, but the module interface has no obvious way to override the null serializer.

谁能提供有关如何覆盖 Jackson 2.0 中的空序列化程序的指针?

Can anyone provide a pointer on how to override the null serializer in Jackson 2.0?

推荐答案

重写 JsonSerializer 序列化方法如下.

Override the JsonSerializer serialize method as below.

public class NullSerializer extends JsonSerializer<Object> {
  public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    // any JSON value you want...  
    jgen.writeString("");
  }
}

然后您可以将 NullSerializer 设置为自定义对象映射器的默认值:

then you can set NullSerializer as default for custom object mapper:

public class CustomJacksonObjectMapper extends ObjectMapper {

public CustomJacksonObjectMapper() {
    super();
    DefaultSerializerProvider.Impl sp = new DefaultSerializerProvider.Impl();
    sp.setNullValueSerializer(new NullSerializer());
    this.setSerializerProvider(sp);
  }
}

或使用 @JsonSerialize 注释为某些属性指定它,例如:

or specify it for some property using @JsonSerialize annotation, e.g:

public class MyClass {

  @JsonSerialize(nullsUsing = NullSerializer.class)
  private String property;
}

这篇关于你如何覆盖 Jackson 2.0 中的空序列化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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