Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey rest server - Return list as json

I'm experiencing a difference in the json structure of a returned list running the same code when running on Tomcat and Glassfish.

@XmlRootElement
public Class Person {
    private int personId;
    private String name;
}

@GET
@Path("/persons")
public Response getPersons()
{
    List<Person> persons = new ArrayList<Person>();
    persons.add(new Person(1, "John Smith"));
    persons.add(new Person(2, "Jane Smith"));

    GenericEntity<List<Person>> entity = new GenericEntity<List<Person>>(Lists.newArrayList<persons)) {};
    Return Response.ok(entity).build();
}

If returned in json format on tomcat (I'm running Tomcat on local machine) the result will be:

[
    {
        "personId" : "1",
        "name" : "John Smith"
    },
    {
        "personId" : "2",
        "name" : "Jane Smith"
    }
]

And if returned in json format on Glassfish (running Glassfish on remote server) the result will be:

{
    "person" : 
    [
        {
            "personId" : "1",
            "name" : "John Smith"
        },
        {
            "personId" : "2",
            "name" : "Jane Smith"
        }
    ]
}

How can I control this format my self? I would prefer the array-format (as on Tomcat) if possible. Either way I want it to produce the same result.

Edit:

Dependencies: jersey-container-servlet (2.14), jersey-server (2.14), jersey-media-moxy (2.14), javax.servlet-api (3.0.1)

Version of Glassfish: 3.1.2.2 (build 5)

Edit 2: It's a problem with Jersey 2.14 and Glassfish 3.x

I just installed Glassfish 3 and 4 and deployed the rest app to check the response. It resulted in different json structure when returning a list. The response from Glassfish 4 was identical to the result I got when running on Tomcat.

like image 908
sjallamander Avatar asked Jan 14 '15 07:01

sjallamander


1 Answers

Try add the response mediatype annotation and try with the List not GenericEntity like this:

 @GET
 @Path("/persons")
 @Produces({ MediaType.APPLICATION_JSON })
 public Response getPersons()
 {
    List<Person> persons = new ArrayList<Person>();
    persons.add(new Person(1, "John Smith"));
    persons.add(new Person(2, "Jane Smith"));

 Return Response.ok(persons).build();
 }
like image 117
FrAn Avatar answered Nov 15 '22 00:11

FrAn