How to serialize in jackson json null string to empty string
I need jackson json (1.8) to seriali开发者_StackOverflow中文版ze a java NULL string to an empty string. How do you do it? Any help or suggestion is greatly appreciated.
Thanks
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(""); } }
精彩评论