java如何使用resful服务返回json数组
这里代码返回JSON
@RequestMapping(method = RequestMethod.GET, value="/json")
public @ResponseBody employee json(HttpServletRequest request) {
String name = request.getParameter("name");
employee ep = new employee();
ep.setResult(name);
return ep;
}
班级员工:
public class employee {
String result;
public employee(){}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public employee(String result) {
this.result = result;
}
}
当我调用url:http://localhost:8080/controller/json?name=abc
我的结果是{"result":"abc"}
但我的期望是{"employee" :[{"result":"abc"}]}
那我怎么做呢
# 1 楼答案
您可以获得以下输出:
通过注释
Employee
类:# 2 楼答案
为了获得预期的json结果,您需要具有以下类型的类:
具有结果属性的类:
类,该类包含具有属性结果的类的列表:
您将获得:
# 3 楼答案
首先,为了使类属性能够映射到JSON数组,该属性应该是集合类型,如List、Set、Map等
然后Spring将结果属性映射到数组。在您的情况下,由于结果属性不是集合,因此不需要将其映射到JSON数组
即使在类中使用集合,也会得到类似的结果}。要获得所需的结果,您需要一个包装器对象。这部分你可以参考Gary的答案
{"result":["abc"]}
但不是{