json - Selecting specific class type from a hierarchy during jackson serialization -
if have class hierarchy -> b, base class, how can specify during jackson serialization include fields base class , exclude subclass? serializing b (the subclass) though.
appreciate help!!
you can use jackson json views mentioned in this similar question.
also can write an annotation introspector or jackson json filter exclude subclass.
i've written example demonstrating how exclude properties type in hierarchy has special annotation.
public class jacksonexcludefromsubclass { @retention(retentionpolicy.runtime) public static @interface ignoretypeproperties {}; public static class superthing { public final string superfield; public superthing(string superfield) { this.superfield = superfield; } } @jsonfilter("filter") @ignoretypeproperties public static class thing extends superthing { public final string thingfield; public thing(string superfield, string thingfield) { super(superfield); this.thingfield = thingfield; } } public static class excludefromsuperclass extends simplebeanpropertyfilter { @override protected boolean include(beanpropertywriter writer) { return true; } @override protected boolean include(propertywriter writer) { if (writer instanceof beanpropertywriter) { annotatedmember member = ((beanpropertywriter) writer).getmember(); return member.getdeclaringclass().getannotation(ignoretypeproperties.class) == null; } return true; } } public static void main(string[] args) throws jsonprocessingexception { thing t = new thing("super", "thing"); objectmapper mapper = new objectmapper(); mapper.setfilters(new simplefilterprovider().addfilter("filter", new excludefromsuperclass())); system.out.println(mapper.writerwithdefaultprettyprinter().writevalueasstring(t)); }
output:
{ "superfield" : "super" }
Comments
Post a Comment