JAX-RS runtime provides XML conversion support out of the box (as we saw in the last tutorial). On the other hand there's no default MessageBodyWriter/MessageBodyReader provider for JSON. But the good news is JAX-RS provides extension points to hookup custom MessageBodyWriter/MessageBodyReader provider. One very easy way to achieve that is to use Jersey support for common media type representations. Jersey JSON support comes as a set of extension modules.
MOXy
Java API for JSON Processing (JSON-P)
Jackson
Jettison
JSON binding support via MOXy is a default and preferred way of supporting JSON binding in a Jersey application. When JSON MOXy module is on the class-path, Jersey will automatically discover the module and seamlessly enable JSON binding support via MOXy in your applications. To return JSON response from our JAX-RS application we have to go through following least necessary steps.
Create a simple Java class to be used as JSON response. Here we can use a class annotated with JAXB annotation (like we did in our last tutorial). This is the easiest approach, if you want to produce/consume both JSON and XML data format. With JAXB beans we will be able to use the same Java model to generate JSON as well as XML representations.
@XmlRootElement
public class Customer {
private String id;
private String name;
private String address;
private String phoneNumber;
public Customer() {
}
public Customer(String id) {
this.id = id;
}
... getters and setters
}
Add @Produces annotation on our service method to declare the media-type as "application/json":
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Customer> getCustomers() {
....
}
To test the application either run the JUnit test CustomerRestServiceTest or run the
embedded tomcat server:
d:\examples\jaxrs-returning-json-response>mvn clean install tomcat7:run-war
and then use the following resource link in your browser.