users@jersey.java.net

Re: Creating Json from XML

From: Tatu Saloranta <tsaloranta_at_gmail.com>
Date: Tue, 30 Nov 2010 09:28:28 -0800

On Tue, Nov 30, 2010 at 4:43 AM, Jonathan Cook - FM&T
<Jonathan.Cook2_at_bbc.co.uk> wrote:
> Hi,
>
> I have a method like this:
>
>         @GET
>    @Path("competition/{comp}")
>     @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
>     public Response getTableXML(@PathParam("comp") String comp) throws
> Exception {
>         LOG.debug("getTableXML()");
>         return Response.ok(findTableXML(comp)).build();
>     }
>
> Jersey doesn’t appear to automatically convert the xml to Json unless you
> are using jaxb. I am not using jaxb so was wondering what the best approach
> was for this in Jersey. I’ve looked at some of the jackson classes I thought
> about maybe using an ObjectMapper but again that appears to only be for use
> with POJOs.

As far as I know, Jersey never converts XML content to JSON or vice
versa. What is done is to use Jettison library which maps Stax API
(xml) calls to read or write JSON, which sort of does convert things,
but only if same interface is being used. This has been done so that
JAXB data binding could be used for JSON data, before Jackson data
binding became available.

The reason why automatic conversion is usually a bad idea is that XML
and JSON content models are fundamentally incompatible, meaning that
resulting XML or JSON "looks ugly", or conversion is not reversible
(one-way). That is, conversion is lossy.

Jersey is completely capable of producing either XML or JSON from
POJOs. This is the usual way to offer data in either format.
And this is the way JAX-RS is designed to work -- XML is an external
data format, and internally data is dealt with as POJOs to be
converted to/from external formats. But not converted between formats,
or used as format-specific objects (dom etc).

If you really want to do conversion, however, you can have a look at
Jettison: you can parse XML using standard XMLStreamReader, and write
JSON using Jettison's mock XMLStreamWriter. This gives you
franken-JSON, which is technically JSON, but looks more like... um...
not sure what exactly. :-)

-+ Tatu +-