EclipseLink/Examples/MOXy/Dynamic/ObjectGraphs

JAXB (JSR-222) makes it easy for you to convert instances of your domain classes to/from XML. The EclipseLink MOXy implementation offers an extension called Dynamic JAXB where instead of real classes you have instances of a map like class called DynamicEntity. You can access the data on your DynamicEntity using get and set methods that take the property name (i.e. customer.get("address") and customer.set('name", "Jane Doe").

In this post, first we will bootstrap a dynamic JAXBContext based on an external mapping file. Then we unmarshal an XML document to dynamic entities, and finally we will apply an object graph to scope the resulting JSON output.

Dynamic Java Model

With a static model the metadata is derived from the Java classes and augmented by any provided metadata (see: JAXB - No Annotations Required). Since in MOXy's dynamic JAXB there are no domain classes the types must be completely defined by metadata. This can be done from an XML schema or as done in this example using MOXy's external mapping document.

oxm.xml

Since there are no real Java classes, in the external mapping document we need to specify each mapping, and for each mapping the type of the Java property.

A jaxb.properties file is used to specify the JAXB provider. For dynamic JAXB the contents of this file are slightly different than usual when using MOXy (compare with Specifying EclipseLink MOXy as your JAXB Provider). This file goes in the same package as the domain model, since here we have a virtual domain model the jaxb.properties file would be the only real item in the example.moxy.objectgraphs.dynamic package.

Demo Code

Below we will explore two different approaches for using object graphs.

Demo - Object Graph Specified through Metadata

In the demo code below we will leverage the object graph that was defined in the external mapping document. The object graph was defined for the dynamic model exactly as it was for the corresponding static model. The only thing that is different is that the object we get from the unmarshal call is an instance of DynamicEntity rather than Customer.

In the demo code below we will create object graph programmatically. The object graph was created for the dynamic model exactly as it was for the corresponding static model (see: MOXy's Object Gaphs - Partial Models on the Fly to/from XML & JSON). What is different is that we used the name of the dynamic entity to create the object graph instead of the class, and we get an instance of DynamicEntity rather than Customer from the unmarshal call.

Below is the same subset as the previous XML document represented as JSON. We have used the new JSON_WRAPPER_AS_ARRAY_NAME property (see Binding to JSON & XML - Handling Collections) to improve the representation of collection values.