When using JAXB in an OSGi container it is important to load the JAXB context into the correct class loader. This is actually an issue with any framework that has not been release for OSGi and uses class loaders. I ran into this when trying to use Restlet's JAXB extension.
The fix is actually pretty easy. When using the JaxbRepresentation it's important to pass the current class loader to the constructor. I extended JaxbRepresentation to make the client code lighter. You can find the code for this below:
Feel free to use the above as you see fit.
One of the thing that can be a bit tricky when using JAXB is to map a java.util.Map to XML. In this example we have a provider object. The provider has a name and a map containing properties.
Below is the provider XML document:
And then the Provider class:
JAXB sees the properties object in the XML document as a list of property entries. Therefore we need to transform the list into a map. To do this we need three supporting classes. The first one is the class containing the entry, or property:
Next we need the class that contains the list of entries, or the properties:
To transform the list into a map we need an XmlAdapter. An XmlAdapter is a class that instructs JAXB on how to marshal and unmarshal an object that does not conform to the JAXB standard. This could for example be a class without a public no args constructor, or as in our case the provider properties map:
Now what is left is to tell JAXB to use the XmlAdaptor when handling the properties field. To do this we use the @XmlJavaTypeAdapter annotation. Below is the fully annotated Provider class: