Extending the CRUD Example: Utilizing JAX-B and Jersey’s JSON

Introduction

In the previous article, REST CRUD:Jersey,Spring and JPA, we made a simple example which linked the technologies: REST, Spring, Jersey and JPA. We will take the example a little further, this time, by engaging the services of JAX-B and Jersey’s JSON. There are some very useful annotations available to quickly make our classes accessible.

Previously when we sent the list of persons, in the database, to the client we did this with JSON but we constructed the JSON object via a utility method. Now with the use of JAX-B 2.x and jersey-json we will do this throught the use of annotations.

From Model to JSON

There are two major steps that occur to transform our objects from the java instance to the JSON representation.

The object is transformed into XML through the annotations provided by JAX-B. The actual transformation occurs behind the scenes involked as part of the following step.

The REST operation on the object is marked-up to produce JSON. This annotation is where the work happens.

On the client side we are already expecting the JSON objects so no change is required. We will go on now to explain how to make these annotations.

Implemenation

New Dependencies

To enable these service a couple more dependencies need to be added to our pom.xml file:

Marking up the Model

The entity we our using in our example is implemented in the Person.java class. To make the Person class available for the JAX-B XML transformation we add two javax.xml.bind annotations. Note that this is a minimal case and there are many options that can be explored to taylor what is exposed to XML. The annotations are:

@XmlAccessorType(XmlAccessType.FIELD)

@XmlRootElement(name = "person")

The annotation express their purpose well. The first indicates that the class fields used to construct the name/value pairs of the JSON object. The second defines the top-level element available to us now through the name ‘person’.

The Source Code

About The Author

David Sells is a computer consultant in Toronto, Ontario who specializing in Java Enterprise Development. He has provided innovative solutions for clients including: IBM, Goldman Sachs, Merrill Lynch and Deutsche Bank.