简体   繁体   English

泽西岛休息服务器 - 返回列表为json

[英]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. 在Tomcat和Glassfish上运行时,我遇到运行相同代码的返回列表的json结构的差异。

@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: 如果在tomcat上以json格式返回(我在本地机器上运行Tomcat),结果将是:

[
    {
        "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: 如果在Glassfish上以json格式返回(在远程服务器上运行Glassfish),结果将是:

{
    "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. 如果可能的话,我更喜欢数组格式(如在Tomcat上)。 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) 依赖关系: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) Glassfish版本:3.1.2.2(版本5)

Edit 2: It's a problem with Jersey 2.14 and Glassfish 3.x 编辑2:这是泽西岛2.14和Glassfish 3.x的问题

I just installed Glassfish 3 and 4 and deployed the rest app to check the response. 我刚刚安装了Glassfish 3和4并部署了其余应用来检查响应。 It resulted in different json structure when returning a list. 返回列表时会产生不同的json结构。 The response from Glassfish 4 was identical to the result I got when running on Tomcat. Glassfish 4的响应与我在Tomcat上运行时得到的结果相同。

Try add the response mediatype annotation and try with the List not GenericEntity like this: 尝试添加响应mediatype注释并尝试使用List not GenericEntity,如下所示:

 @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();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM