gpt4 book ai didi

java - REST - 定义来自 Restful Java 服务的 JSON 数组的名称

转载 作者:行者123 更新时间:2023-12-01 21:50:11 25 4
gpt4 key购买 nike

我在 Glassfish 服务器中运行的 REST Java 服务中获得了以下函数:

serviceTest.java

@Path("/servicetest")
public class serviceTest{
@GET
@Path("/findall")
@Produces(MediaType.APPLICATION_JSON)
public List<Person> findAll(){
List <Person> result = new ArrayList<>();
result.add(new Person("1", "Charlie");
result.add(new Person("2", "Mary");
return result;
}
}

我还定义了一个类:

person.java

public class person {

private String id;
private String name;

public person(String id, String name) {
this.id = id;
this.name = name;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

当我从客户端或 Web 浏览器调用 findAll() 函数时,我得到以下格式的 JSON 对象:

[
{
"id": "1",
"name": "Charlie"
},

{
"id": "2",
"name": "Mary"
}
]

但是我需要通过名称来识别 JSON 数组,如下所示:

{"person":
[
{
"id": "1",
"name": "Charlie"
},

{
"id": "2",
"name": "Mary"
}
]
}

我怎样才能做到这一点...?提前致谢...

最佳答案

您可以将人员列表包装在 map 中:

public Map<String,List<Person>> findAll(){
List <Person> list = new ArrayList<>();
list.add(new Person("1", "Charlie");
list.add(new Person("2", "Mary");
LinkedHashMap<String,List<Person>> map = new LinkedHashMap<>();
map.put("person", list);
return map;
}

关于java - REST - 定义来自 Restful Java 服务的 JSON 数组的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35350184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com