Jersey leisure server - back to list as json

I experience a difference in the json structure of the returned list using the same code when working 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 it is returned in json format on tomcat (I am running Tomcat on the local machine), the result will be:

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

And if it returns in json format on Glassfish (running Glassfish on a remote server), the result will be:

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

How can I control this format myself? I would prefer an array format (like on Tomcat), if possible. In any case, I want him to give 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)

Glassfish Version: 3.1.2.2 (Build 5)

Edit 2: This is a problem with Jersey 2.14 and Glassfish 3.x

I just installed Glassfish 3 and 4 and deployed the application for the rest to check the answer. This led to a different json structure when returning the list. The answer from Glassfish 4 was identical to the result I got when working on Tomcat.

+6
source share
1 answer

Try adding an annotation to the response mediate and try using 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(); } 
+1
source

Source: https://habr.com/ru/post/980968/


All Articles