• REST
    April 23, 2008

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

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();

you will get

while if you add one more element

you will get this:
{"list":["one", "two"]}

Please note the missing brackets at the former case.


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:

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_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


Join the discussion

Comments ( 1 )
  • Brill Pappin Thursday, April 1, 2010

    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?

Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.