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
All replies. You can use XmlElement attribute and specify that value should be nullable. Then the empty element will be serialized with correct nil value.
Serialize Null Fields Fields/PropertiesWith its default settings, Jackson serializes null-valued public fields. In other words, resulting JSON will include null fields. Here, the name field which is null is in the resulting JSON string.
You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.
We can force Gson to serialize null values via the GsonBuilder class. We need to call the serializeNulls() method on the GsonBuilder instance before creating the Gson object. Once serializeNulls() has been called the Gson instance created by the GsonBuilder can include null fields in the serialized JSON.
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(""); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With