users@jersey.java.net

[Jersey] Trying to figure out JSON formatting issue

From: Roll, Stuart L <Stuart.Roll_at_ca.com>
Date: Mon, 16 May 2011 11:56:09 -0400

Greetings -

 

I'm pretty new to Jersey and I've run into a problem that I just can't
seem to research my way out of. I want to support both XML and JSON
serialization and for JSON I want a format that would work well for a
potential JavaScript client but could also work easily with the Jersey
client. That led me to choose the "natural" format for JSON which, in
turn, led me to my problem.

 

Let's say I have two resources, one of which returns a single instance
of my JAXB object and another that returns a List of them. My client
requests would look something like:

 

MyBean mb =
webResource.accept(MediaType.APPLICATION_JSON).get(MyBean.class);

 

List<MyBean> mbs =
webResource.accept(MediaType.APPLICATION_JSON).get(new
GenericType<List<MyBean>>() {});

 

If my server JSON configuration is this:



JSONConfiguration.natural()

 

Then single object return works just fine but returning a list fails
("[javax.xml.bind.UnmarshalException: unexpected element (uri:"",
local:"id"). Expected elements are <{}myBean>]".

 

If I correct that by switching to this server JSON configuration:

 

JSONConfiguration.natural().rootUnwrapping(false)

 

Then returning a list works just fine but for the single object return I
get an uninitialized object (no errors but values are all null or
false).

 

So my first question is "What JSON formatting should I be using to make
JavaScript people happy (I am not one of them), or alternatively for the
greatest interoperability?".

 

Secondly, is there some way to configure this so Jersey clients could
work for both objects and lists of objects?

 

Stuart