我在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"
}
]
}
我该怎么做......?提前谢谢......
答案 0 :(得分:2)
您可以将人员列表包装在地图中:
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;
}
答案 1 :(得分:1)
使用单个字段将List<Person>
包裹在一个类中:
public class PersonResponse {
private List<Person> person = new ArrayList<Person>();
public PersonResponse(List<Person> person) {
this.person = person;
}
}
将您的REST方法更改为:
public PersonResponse findAll(){
List <Person> result = new ArrayList<>();
result.add(new Person("1", "Charlie");
result.add(new Person("2", "Mary");
return new PersonResponse(result);
}
}