How do you redefine null serializer in Jackson 2.0?

I use Jackson to serialize JSON, and I would like to override the null serializer - in particular, so that null values ​​are serialized as empty strings in JSON, and not in the "null" string.

All the documentation and examples I found on how to install null serializers refer to Jackson 1.x - for example, the code below http://wiki.fasterxml.com/JacksonHowToCustomSerializers is no longer compiled with Jackson 2.0 because StdSerializerProvider is no longer does not exist in the library. This web page describes the Jackson 2.0 module interface, but the module interface does not have an obvious way to override the zero serializer.

Can someone point a pointer to how to override the zero serializer in Jackson 2.0?

+3
source share
1 answer

Override the JsonSerializer serialization method as shown 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(""); } } 

And then create a custom mapper object and set the NullSearilizer to the default serializer, as shown below.

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

Source: https://habr.com/ru/post/974766/


All Articles