I'm using Jackson 2.4 to serialize objects to JSON.
When I serialize a list of objects, having some elements are null, the result JSON
string contains some "null" strings.
How do I prevent "null"
elements from being serialized? Is there any configuration for ObjectMapper
? I have already set "setSerializationInclusion(Include.NON_NULL)"
!
Here is my code :
List<String> strings = new ArrayList<>();
strings.add("string 1");
strings.add("string 2");
strings.add(null);
strings.add(null);
After serializing I got this :
[string 1, string 2, null, null]
How do I get the JSON string without "null"?
[string 1, string 2]
Using @JsonInclude annotation.
@JsonInclude(Include.NON_NULL)
class Foo {
String bar;
}
Edit
Also you can create your own serializer.
For example :
public static void main(String[] args) throws JsonProcessingException {
List<String> strings = new ArrayList<>();
strings.add("string 1");
strings.add("string 2");
strings.add(null);
strings.add(null);
ObjectMapper mapper=new ObjectMapper();
mapper.getSerializerProvider().setNullValueSerializer(new NullSerializer());
System.out.println(mapper.writeValueAsString(strings));
}
NullSerializer.java
class NullSerializer extends JsonSerializer<Object>
{
@Override
public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused)
throws IOException, JsonProcessingException
{
jsonGen.writeFieldName("");
}
}
Will print
["string 1","string 2","",""]
then you can remove jsonGen.writeFieldName(""); to print
["string 1","string 2"]
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