【问题标题】:Java - Spring return JSON object / arrayJava - Spring 返回 JSON 对象/数组
【发布时间】:2016-12-14 21:57:54
【问题描述】:

我有一个基本的 Rest Controller,它以 json 格式向客户端返回模型列表:

@RestController
public class DataControllerREST {

    @Autowired
    private DataService dataService;

    @GetMapping("/data")
    public List<Data> getData() {
        return dataService.list();
    }

}

以这种格式返回数据:

[

    {
        "id": 1,
        "name": "data 1",
        "description": "description 1",
        "active": true,
        "img": "path/to/img"
    },
    // etc ...

]

这很适合开始,但我考虑返回这种格式的数据:

[
    "success": true,
    "count": 12,
    "data": [
        {
            "id": 1,
            "name": "data 1",
            "description": "description 1",
            "active": true,
            "img": "path/to/img"
        },
        {
            "id": 2,
            "name": "data 2",
            "description": "description 2",
            "active": true,
            "img": "path/to/img"
        },
    ]
    // etc ...

]

但我不确定这个问题,因为我无法将任何类作为 JSON 返回...有人有建议或建议吗?

问候和感谢!

【问题讨论】:

  • 当您的 JSON 以“[”开头时,这意味着它是一个数组。您实际上是指一个数组还是一个对象 ({}),其中包含一个 data 数组?

标签: java json spring rest controller


【解决方案1】:

“因为我不能将任何类作为 JSON 返回”- 谁说的?

事实上,这正是你应该做的。在这种情况下,您将需要创建一个包含所有所需字段的外部类。它看起来像这样:

public class DataResponse {

    private Boolean success;
    private Integer count;
    private List<Data> data;

    <relevant getters and setters>
}

你的服务代码会变成这样:

@GetMapping("/data")
public DataResponse getData() {
    List<Data> results = dataService.list();
    DataResponse response = new DataResponse ();
    response.setSuccess(true);
    response.setCount(results.size());
    response.setData(results);
    return response;
}

【讨论】:

  • 嘿,感谢您的回答,我提到了抱怨的“转换器”:“ org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 java.lang.IllegalArgumentException:没有转换器发现返回值类型为:class com.example.app.rest.controller.DataResponse" 你有什么建议吗?
  • 您是否为 DataResponse 添加了相关的 getter 和 setter?是Jackson included as part of your project
猜你喜欢
  • 2020-02-11
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 1970-01-01
  • 2019-12-09
  • 2014-05-12
  • 1970-01-01
相关资源
最近更新 更多