Hi Frank,
i will explain and suggest a solution bellow.
the reason is that your bean gets translated into the following
in XML:
only one item in the list:
<buildings>b1</buildings>
two items:
<buildings>b1</buildings><buildings>b2</buildings>
JSON writer works at XML Infoset level, (not in the JAXB model
level), so there is no way to recognize the former case was an array (list).
However, you can provide a simple hint to the JSON writer
via creating a custom JSONJAXBContext for your bean:
@Provider
public static class JAXBContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class[] types = {BuildingList.class};
public JAXBContextResolver() throws Exception {
Map<String, Object> props = new HashMap<String, Object>();
props.put(JSONJAXBContext.JSON_NOTATION, "MAPPED");
props.put(JSONJAXBContext.JSON_ROOT_UNWRAPPING, Boolean.TRUE);
props.put(JSONJAXBContext.JSON_ARRAYS, "[\"buildings\"]");
this.context = new JSONJAXBContext(types, props);
}
public JAXBContext getContext(Class<?> objectType) {
return (types[0].equals(objectType)) ? context : null;
}
}
Hope this helps,
~Jakub
On Fri, Apr 04, 2008 at 10:50:58AM -0500, Frank Martínez wrote:
> Hi Guys,
>
> Does anybody know why a list with an unique element is serialized as a
> JSonObject instead of a JSonArray with one element?
>
> i.e.
>
> POJO to be serialized:
>
> @XmlRootElement
> public class BuildingList {
>
> @XmlElement
> private List<Building> buildings;
>
> public BuildingList(List<Building> buildings) {
> this.buildings = buildings;
> }
>
> public BuildingList() {
> }
>
> }
>
> Resource method:
>
> @GET
> @ProduceMime("application/json")
> public BuildingList getJson() {
>
> BuildingDAO dao = ConfigServlet.getSession().getDAO(BuildingDAO.class);
> List<Building> list = dao.findAll();
> return new BuildingList(list);
>
> }
>
>
> Result:
>
> If there are more than one element:
>
> {"buildings":[ { ... }, { ... }, ... ]}
>
> But if there are just one element:
>
> {"buildings": { ... } }
>
> The problem is that the Javascript client is awaiting for an array.
>
> Any ideas?
>
> Thanks,
> Frank.
>
>
> --
> Frank D. Martínez M.
> Asimov Technologies Ltda.
> Blog: http://www.ibstaff.net/fmartinez/
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_jersey.dev.java.net
> For additional commands, e-mail: users-help_at_jersey.dev.java.net
>