有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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"}]}

那我怎么做呢


共 (3) 个答案

  1. # 1 楼答案

    您可以获得以下输出:

    {
        "employee": {
            "result": "abc"
        }
    }
    

    通过注释Employee类:

    @JsonTypeInfo(include=JsonTypeInfo.As.WRAPPER_OBJECT, use=Id.NAME)
    public class employee {
        // same class body
    }
    
  2. # 2 楼答案

    为了获得预期的json结果,您需要具有以下类型的类:

    具有结果属性的类:

    class Second{
    
      String result;
    
      public Second(String r){
        this.result = r;
      }
    
      public String getResult() {
         return result;
      }
      public void setResult(String result) {
        this.result = result;
      }
    }
    

    类,该类包含具有属性结果的类的列表:

    class Employee{
    
        List<Second> employee  = new ArrayList<Second>();
    
        public List<Second> getEmployee() {
            return employee;
        }
        public void setEmployee(List<Second> s) {
            this.employee = s;
        }
    }
    

    您将获得:

    {"employee":[{"result":"aaa"},{"result":"bbb"},{"result":"ccc"}]}
    
  3. # 3 楼答案

    首先,为了使类属性能够映射到JSON数组,该属性应该是集合类型,如List、Set、Map等

    public class employee {
        List<String> result;
        public employee(){}
    
        public List<String> getResult() {
            return result;
        }
    
        public void setResult(List<String> result) {
            this.result = result;
        }
        public employee(String result) {
            this.result = result;
        }
    }
    

    然后Spring将结果属性映射到数组。在您的情况下,由于结果属性不是集合,因此不需要将其映射到JSON数组

    即使在类中使用集合,也会得到类似的结果 {"result":["abc"]}但不是{}。要获得所需的结果,您需要一个包装器对象。这部分你可以参考Gary的答案