java - @jsonproperty serialize different pojo elements in the same attribute name -
i have simple pojo
public class c { public string f1; public integer f2; }
at runtime sure @ 1 of fields not null (i.e. if f1
"hello"
, i'm sure f2
null
, , vice versa)
i serialize object using same name; example, with
c c1 = new c(); c1.f1 = "hello" c c2 = new c(); c2.f2 = integer.valueof(99)
i have c1
serialized {"samekey":"hello"}
, c2
{"samekey":99}
.
i know can use @jsonproperty
set serialized name, cannot set same name both fields.
is there way that?
here customserializer, checks if f2 value not null f2 value copied f1 , making f2=null.and excluding nulls in model 1 key&value other 1 null.
public class customserializer extends jsonserializer<c> { @override public void serialize(final c c, final jsongenerator gen, final serializerprovider serializers) throws ioexception, jsonprocessingexception { if(c.getf2() != null) // considering need f1 key && value { c.setf1(c.getf2().tostring()); c.setf2(null); } }
}
annotate serializer & notnull in model as
@jsonserialize(using = customserializer.class) @jsoninclude(jsoninclude.include.non_null) public class c { private string f1; private integer f2; //getters & setters }
hope expecting.
Comments
Post a Comment