Missing Brackets At JSON One-Element Arrays In Jersey

It is a bit uncomfortable, but if you need to deal with arrays in JSON produced by Jersey,
you will need to provide a custom JAXB context resolver to make sure brackets are properly used
in one-element arrays.

As Reece Garrett pointed out,
the very same issue was hit (and resolved) in Jettison as well.

What is exactly the issue?

Lets say, you have the following JAXB bean


@XmlRootElement
public class ArrayWrapper {
public List<String> list = new LinkedList<String>();
}

and want to get JSON out of it. The issue is, that after


ArrayWrapper aw = new ArrayWrapper();
aw.list.add("one");

you will get


{"list":"one"}

while if you add one more element


aw.list.add("two");

you will get this:


{"list":["one", "two"]}

Please note the missing brackets at the former case.

Solution

In order to have the brackets properly used also for one-element arrays you need to provide your
custom JAXB context through which you can tell the underlying JSON writer what is an array.

It can look like this:


@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {

private JAXBContext context;
private Class[] types = {ArrayWrapper.class};

public JAXBContextResolver() throws Exception {
Map props = new HashMap<String, Object>();
props.put(JSONJAXBContext.JSON_NOTATION, "MAPPED");
props.put(JSONJAXBContext.JSON_ROOT_UNWRAPPING, Boolean.TRUE);
props.put(JSONJAXBContext.JSON_ARRAYS, "[\\"list\\"]");
this.context = new JSONJAXBContext(types, props);
}

public JAXBContext getContext(Class<?> objectType) {
return (types[0].equals(objectType)) ? context : null;
}
}

JSONJAXBContext.JSON_ARRAYS property here takes a JSON array with names of elements representing arrays
in you JAXB beans. Having the resolver in place for the example above you will now obtain


{"list":["one"]}

Comments:

Thanks for that... it's maddening that they still haven't fixed the issue!

I'm also having a nightmare with strange date formatting... any idea how to set the date formatting?

Posted by Brill Pappin on April 01, 2010 at 09:38 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Jakub Podlesak

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today