java - JAXB Marshall XML Profile Filter -
i have need marshall object xml using jaxb.
the marshall / unmarshall code works fine, want filter resulting xml based on annotation.
xmlprofile.java
@retention (runtime) @target({type, method, field}) public @interface xmlprofile { string[] value(); }
foopojo.java
@xmlrootelement @xmlaccessortype(xmlaccesstype.field) public class foopojo { @xmlelement @xmlprofile("config") public string bar; @xmlelement @xmlprofile("operational") public string bartender; @xmlelement @xmlprofile({"config", "operational"}) public string spy; }
i read jaxb documentation, have not found examples / topics on how inject code marshall process, different adapter or eventhandlers.
in particular read event handlers, found support of before marshal / after marshal events.
i expected found beforefieldmarshal event not possible, figured write piece of code scans current entity , set null properties not matching current profile:
private class profilelistener extends marshaller.listener { private string profile; public profilelistener(string profile) { this.profile = profile; } @override public void beforemarshal(object source) { if (source == null || profile == null || profile.length() == 0) return; field[] fields = source.getclass().getfields(); (field f : fields){ xmlprofile xmlprofile = f.getannotation(xmlprofile.class); if (xmlprofile == null) continue; string[] annvalues = xmlprofile.value(); if (annvalues == null || annvalues.length == 0 || findinarray(annvalues)) { continue; } // remove object f.setaccessible(true); try { f.set(source, null); } catch (exception e) { e.printstacktrace(); } } super.beforemarshal(source); //to change body of generated methods, choose tools | templates. } private boolean findinarray(string[] annvalues){ (string annval : annvalues) { if (profile.equalsignorecase(annval)){ return true; } } return false; } }
the code works fine, nested object, code obtain:
working pojo
foopojo foopojo = new foopojo(); foopojo.bar = "tijuana cafe"; foopojo.bartender = "cynthia"; foopojo.spy = "antony fisco"; foopojo.phone = "555 555 555";
** resulting xml config profile:**
<foopojo> <bar>tijuana cafe</bar> <spy>antony fisco</spy> <phone>555 555 555</phone> </foopojo>
** resulting xml operational profile:**
<foopojo> <bartender>cynthia</bartender> <spy>antony fisco</spy> <phone>555 555 555</phone> </foopojo>
but has functional bug don't know how solve: pojo updated code, setting null properties.
is there better way that? can clone object , work on it, i'm not sure right way.
Comments
Post a Comment