如何覆盖Jackson 2.0中的null序列化程序



我使用Jackson进行JSON序列化,我想覆盖null序列化程序——特别是,这样null值在JSON中被序列化为空字符串,而不是字符串"null"。

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

有人能提供一个指针来说明如何在Jackson 2.0中重写null序列化程序吗?

覆盖JsonSerializer序列化方法,如下所示。

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设置为自定义对象映射程序的默认值

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

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

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

我没能得到公认的答案来为我工作。也许是因为我的ObjectMapper在我的环境中是一个Spring Bean。

我恢复使用SimpleModule。相同的序列化程序:

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

注释位于Mixin中,因为我无法修改MyClass:

public abstract class MyClassMixin {
    @JsonSerialize(nullsUsing = NullSerializer.class)
    public String property;
}

为了将序列化程序连接到映射程序,我在Spring组件中使用了一个模块:

@AutoWired
ObjectMapper objectMapper;
@PostConstruct
public void onPostConstruct() {
    SimpleModule module = new SimpleModule();
    module.setMixInAnnotation(MyClass.class, MyClassMixin.class);
    objectMapper.registerModule(module);
}

最新更新