I have a requirement, to marshall/unmarshall some elements of java pojo depending upon a custom annotation marked on the field. suppose there are 3 fields in my java pojp
@CustomVersion("v1")
private String field1;
@CustomVersion("v1","v2")
private String field2;
@CustomVersion("v2")
private String field3;
i would like to marshall only the fields with v1 if i pass version="v1" parameter while conversion in jaxb. if i pass v2, all fields with v2 annotation should only be marshalled.
is that even possible using jaxb? i am sure selective marshalling would be supported through some library or way, am not still able to figure it out after quite some searching. any help or advice or pointers are highly appreciated.
First of all I would suggest doing such preprocessing before marshalling. It would be much easier. However if it is not possible for some reason then you can create you custom type adapter. Then you can put
@XmlJavaTypeAdapter(VersioningAdapter.class)
on every type that you want to have versioning enabled.@XmlJavaTypeAdapter
can also be specified on package level, but you have to specify to which types it applies. You cannot useXmlAdapter
without specifying somewhere@XmlJavaTypeAdapter
.Drawbacks of such solution:
@XmlJavaTypeAdapter
@XmlJavaTypeAdapter
does not work for root element, only on child elements. You have to call adapter manually on root element before marshallingAFAIK there is no other option for customizing JAXB marshalling. That's why I think that annotation processing should be performed in separate step before marshalling. Unless you can accept mentioned limitations.
Sample adapter (full code can be found here):
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
Below is an example of how you could use MOXy's
@XmlNamedObjectGraphs
extension to map your use case.Java Model
Foo
The
@XmlNamedObjectGraphs
extension allows you to specify multiple subsets of mappings identified by a key.jaxb.properties
To use MOXy as your JAXB provider you need to include a file called
jaxb.properties
with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).Demo Code
Demo
You can specify the key corresponding to the object graph to have that subset applied to the object you are marshalling.
Output
For More Information