Wednesday Apr 23, 2008
Wednesday Apr 23, 2008
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>();
}
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.
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"]}
Friday Apr 11, 2008
Včera jsem měl velkou čest zúčastnit se historicky vůbec prvního setkání tzv. Java Teamu na Slovensku.

Javateam je něco, co v Čechách známe pod pojmem Java User Group. (všimněte si, jak velmi neanglicky/neamericky oba typy označení působí). Vystoupil jsem s prezentací projektu GlassFish -- Java EE 5 aplikačního serveru, přičemž polovinu "slajdů" jsem "převzal" od Martina Grebače a druhou polovinu od Alexis Moussine-Pouchkine(a). "Pánové: ďakujem, merci bien, спасибо!" Výslednou kompilaci slajdů můžete vidět zde.