14

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

1

1 Answer 1

11

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("");
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @streetturtle, that's it.
what about converting non-existent attributes that are String type so they are empty string to. This only seemed to work if something was null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.