Tuesday, August 07, 2007

Using JAXB to generate XML and JSON from a single HTTP method

I just read this post from Paul Sandoz on the Jersey mailing list ( Jersey is the open source JAX-RS (JSR 311) Reference Implementation for building RESTful Web services.

They've been working on using JAXB to support both XML and JSON bindings.

Paul's recent checkin allows you to annotate a single method with JAXB annotations to support JSON and XML data formats as a response.

Which format is used depends upon the accept header of the HTTP request. If there is no accept header or it is set to *, application/* or application/xml then you get XML. If it's application/json, then you get JSON.

Here is an example from Paul's email:

@UriTemplate("/")
public class MyResource {
@HttpMethod
@ProduceMime({"application/xml", "application/json"})
public JAXBBean get() {
JAXBBean j = ...
return j;
}
}

Note that this is very in line with REST principles. The response is a representation of the state, and you can get different representations of that state for the same request, depending upon what the request asks for.

Pretty darn cool - great work, guys!