users@jersey.java.net

Differences in json and xml responses

From: <james.lorenzen_at_accenture.com>
Date: Thu, 16 Sep 2010 16:18:43 -0400

We are writing some simple jersey services written in groovy that return basic lists of objects and are getting different results between json and xml.

Here is our Person model

@XmlAccessorType( XmlAccessType.FIELD )
@XmlRootElement
class Person {
    String name
}

Here is our Service

@GET
@Produces(["application/json", "application/xml"])
public List<Person> getPersons() {
    return Manager.getPersons()
}

For XML this returns what we want:

<persons>
    <person>
        <name>James</name>
    </person>
</persons>

But for JSON the named array is singular which is not what we want:

{"person": ["name": "James"]}

So to get around the JSON response not having a plural named array we introduced the Persons model object:

@XmlAccessorType( XmlAccessType.FIELD )
@XmlRootElement
class Persons {
    List<Person> persons
}

We update our Service to:

public Persons getPersons()

The result is now JSON has the correct plural named array, but the XML response now has duplicate persons elements, which is not what we want.
<persons>
    <persons>
        <name>James</name>
    </persons>
</persons>

So it appears that we can't get consistent results for XML and JSON. Ideally I'd love not to have to create a Persons object. In fact I think the easiest thing would be to support an annotation on the Service that lets us define the root element. Something like this:

@GET
@Produces(["application/json", "application/xml"])
@XmlRootElement(name="persons")
public List<Person> getPersons() {
    return Manager.getPersons()
}


This message is for the designated recipient only and may contain privileged, proprietary, or otherwise private information. If you have received it in error, please notify the sender immediately and delete the original. Any other use of the email by you is prohibited.