Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
Below is how you could support this use case with MOXy as your JSON-binding provider.
Java Model
By default a JAXB implementation will convert a byte[]
to base64Binary. You can use the HexBinaryAdapter
to have it represented as hexBinary.
package forum15643723;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
private byte[] foo;
@XmlJavaTypeAdapter(HexBinaryAdapter.class)
private byte[] bar;
}
Demo
In the demo code below we will read the JSON into objects and then write it back to JSON.
package forum15643723;
import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {Root.class}, properties);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource json = new StreamSource("src/forum15643723/input.json");
Root root = (Root) unmarshaller.unmarshal(json, Root.class).getValue();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
jaxb.properties
To specify MOXy as your JAXB provider you need to include a file called jaxb.properties
in the same package as your domain model (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
input.json/Output
The foo
and bar
properties represent the same data. foo
is represented as base64Binary and bar
is represented as hexBinary.
{
"foo" : "3q2+78r+",
"bar" : "DEADBEEFCAFE"
}
For More Information