jun
jun

Reputation: 141

How to serialize in jackson json null string to empty string

I need jackson json (1.8) to serialize a java NULL string to an empty string. How do you do it? Any help or suggestion is greatly appreciated.

Thanks

Upvotes: 14

Views: 38779

Answers (1)

enigment
enigment

Reputation: 3616

See the docs on Custom Serializers; there's an example of exactly this, works for me.

In case the docs move let me paste the relevant answer:

Converting null values to something else

(like empty Strings)

If you want to output some other JSON value instead of null (mainly because some other processing tools prefer other constant values -- often empty String), things are bit trickier as nominal type may be anything; and while you could register serializer for Object.class, it would not be used unless there wasn't more specific serializer to use.

But there is specific concept of "null serializer" that you can use as follows:

// Configuration of ObjectMapper:
{
    // First: need a custom serializer provider
   StdSerializerProvider sp = new StdSerializerProvider();
   sp.setNullValueSerializer(new NullSerializer());
   // And then configure mapper to use it
   ObjectMapper m = new ObjectMapper();
   m.setSerializerProvider(sp);
}

// serialization as done using regular ObjectMapper.writeValue()

// and NullSerializer can be something as simple as:
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("");
   }
}

Upvotes: 11

Related Questions