users@jersey.java.net

Re: [Jersey] JSON Notation

From: Jakub Podlesak <Jakub.Podlesak_at_Sun.COM>
Date: Thu, 19 Jun 2008 17:15:02 +0200

Hi Marcel,

please see inline...

On Thu, Jun 19, 2008 at 08:31:00AM -0600, Marcel Thibault wrote:
> Hello,
>
> Using the following XML doc:
>
> <list>
> <item>
> <id1>val1<id1>
> <id2>val2<id2>
> <item>
> <item>
> <id1>val1<id1>
> <id2>val2<id2>
> <item>
> ....
> </list>
>
> I am trying to get the following JSON notation:
>
> {[{"id1":"val1", "id2":"Val2"},{"id1":"val1","id2","val2"}]}

I am afraid, for the moment, you would need to use low level JSONArray provider.
I.e. to return JSONArray instead of JAXBBean to be serialized out.

In fact, what you want to get is not a valid JSON (see [1]), you would need to have only:

[{"id1":"val1", "id2":"Val2"},{"id1":"val1","id2","val2"}]

as in a JSON object {} you can not have only a value (the array in your case) without a key ("item").

>
> Jersey comes close to rendering this format but I can't seem to get rid of the "item" text.
>
> I get the following:
> {"item":[{"id1":"val1", "id2":"Val2"},{"id1":"val1","id2","val2"}]}
>
> I am using the following code for my ContextResolver:
>
> @Provider
> public class JAXBContextResolver implements ContextResolver<JAXBContext> {
>
> private JAXBContext context;
> private Class[] types = {List.class, Item.class};
>
> public JAXBContextResolver() throws Exception {
> Map<String, Object> props = new HashMap<String, Object>();
> props.put(JSONJAXBContext.JSON_NOTATION, JSONJAXBContext.JSONNotation.MAPPED.toString());
> props.put(JSONJAXBContext.JSON_ROOT_UNWRAPPING, Boolean.TRUE);
> props.put(JSONJAXBContext.JSON_ARRAYS, "[\"Item\"]");
> this.context = new JSONJAXBContext(types, props);
> }
>
> public JAXBContext getContext(Class<?> objectType) {
> for (Class type : types) {
> if (type == objectType) {
> return context;
> }
> }
> return null;
>
> }
> }
>
> Is it possible to strip the extra "item" text from the JSON structure using a ContextResolver

Not at the moment (0.8 version). However i will probably look at what is possible in this area
and (if possible) try to add some config options for such cases in 0.9 timeframe.
I am however definitely not going to introduce an option providing
possibility to generate an invalid JSON data.

Thank you a lot for your use case!

~Jakub

[1]http://www.json.org/

>
> Thanks,
>
> Marcel Thibault
>
>
>

-- 
http://blogs.sun.com/japod