Sunday, September 17, 2017

Jackson and JAXB annotations


what is this article about?

When using REST apis that expose JSON objects, the popular solution is to decorate your Java objects with annotations (like \@JsonProperty) and have the underlying framework serialize your objects to JSON. But what happens when your java objects were created from xsd-s? This article shows one way to handle this with minimal changes.

what are Jackson and JAXB annotations?

Jackson annotations are annotations that control how a java object get serialized into JSON. An example of this that is widely used is \@JsonProperty. More about Jackson annotations at http://www.baeldung.com/jackson-annotations

JAXB annotations are annotations that control how a java object gets serialized into XML (mostly). However, these can be used to serialize into JSON also. More about JAXB annotations at http://www.techferry.com/articles/jaxb-annotations.html

where do they come from?

JAXB annotations usually come from xjc which is used to create java classes from xsd specifications. Jackson annotations are usually added manually to java classes.

how are they used?

When you need to serialize a java object into JSON (usually for the result of a REST api), a Jackson ObjectMapper is used (usually by the framework). This objectmapper may be configured to use Jackson annotations or JAXB annotations or both. When the objectmapper.readValueAsString() is used to convert an object to json, it will use the runtime annotations within the object to serialize field-names and format values appropriately. If both annotations are configured, then the order in which they are specified determines which one is used.


 AnnotationIntrospector annotationInspector = new AnnotationIntrospectorPair(

new JacksonAnnotationIntrospector(), 
                                                new JaxbAnnotationIntrospector(
                                                      objMapper.getTypeFactory())
 objMapper.setAnnotationIntrospector(annotationInspector);

how to use JAXB annotations in Consumers?

When consuming the rest apis as a client, you can use javax.ws.rs.client.Client. More about how to use this is https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-2rd-edition/en/part1/chapter8/client_and_web_target.html .

The Client can be configured to use a JacksonJaxbJsonProvider. This is achieved by getting a client from a ClientBuilder which is configured to use the JacksonJaxbJsonProvider. Then whenever the WebTarget uses any java objects for input/output, it will serialize these with both Jackson and Jaxb annotations. 

how to use JAXB annotations in Producers?

Jersey applications by default use JAXB and Jackson annotations. See https://github.com/jasonray/jersey-starterkit/wiki/serializing-a-pojo-to-xml-or-json-using-jaxb for more information.





No comments:

Post a Comment