users@jersey.java.net

[Jersey] Re: Creating Json from XML

From: Jakub Podlesak <jakub.podlesak_at_oracle.com>
Date: Tue, 14 Dec 2010 17:00:46 +0100

Hi Jonathan,

I would second Tatu's suggestion, that except for some very corner cases,
Jackson gives you the most useful JSON representation for your Java
objects,
and you should stick with that.

To configure Jersey to use the Jackson provider, you can just use the
following
ResourceConfig feature, as described in [1]:

          <init-param>
              <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
              <param-value>true</param-value>
          </init-param>

HTH,

~Jakub



[1]http://jersey.java.net/nonav/documentation/latest/json.html#d0e1960



On 11/30/2010 06:28 PM, Tatu Saloranta wrote:
> 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 +-
>