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.
Lets say, you have the following JAXB bean
@XmlRootElement
public class ArrayWrapper {
public List<String> list = new LinkedList<String>();
}
ArrayWrapper aw = new ArrayWrapper();
aw.list.add("one");
{"list":"one"}
aw.list.add("two");
{"list":["one", "two"]}
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 {
Mapprops = 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"]}
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?