java - Jackson - serializing a list containing null elements -
i'm using jackson 2.4 serialize objects json.
when serialize list of objects, having elements null, result json
string contains "null" strings.
how prevent "null"
elements being serialized? there configuration objectmapper
? have set "setserializationinclusion(include.non_null)"
!
here code :
list<string> strings = new arraylist<>(); strings.add("string 1"); strings.add("string 2"); strings.add(null); strings.add(null);
after serializing got :
[string 1, string 2, null, null]
how json string without "null"?
[string 1, string 2]
using @jsoninclude annotation.
@jsoninclude(include.non_null) class foo { string bar; }
edit
also can create own serializer.
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 can remove jsongen.writefieldname(""); print
["string 1","string 2"]
Comments
Post a Comment