Japod's blog
Archives
« April 2008 »
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
12
13
14
15
16
17
18
19
20
21
22
24
25
26
27
28
29
30
   
       
Today
Click me to subscribe
Search

Links
 

View My Stats
« Previous month (Mar 2008) | Main | Next month (May 2008) »
Wednesday Apr 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


@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"]}

Posted at 03:41PM Apr 23, 2008 by Jakub Podlesak in REST  |  Comments[0]

Friday Apr 11, 2008
Historicky první setkání Java teamu na Slovensku

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.

Posted at 12:45AM Apr 11, 2008 by Jakub Podlesak in Hezky česky  |  Comments[0]