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

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

问题描述

我正在使用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中使用null序列化程序?

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);
  }
}

或使用<$ c $为某些房产指定c> @JsonSerialize 注释,例如:

public class MyClass {

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

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

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