简体   繁体   English

Java - Spring 返回 JSON 对象/数组

[英]Java - Spring return JSON object / array

I have a basic Rest Controller which returns a list of models in json to the client:我有一个基本的 Rest 控制器,它将 json 中的模型列表返回给客户端:

@RestController
public class DataControllerREST {

    @Autowired
    private DataService dataService;

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

}

Which returns data in this format:它以这种格式返回数据:

[

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

]

Thats great for starting, but i thought about returning data of this format:这非常适合开始,但我考虑过返回这种格式的数据:

[
    "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 ...

]

But i am not sure about this issue as i can not return any class as JSON... anybody has suggestions or advices?但我不确定这个问题,因为我不能将任何类作为 JSON 返回......有人有建议或建议吗?

Greetings and thanks!问候和感谢!

"as i can not return any class as JSON" - says who? “因为我不能将任何类作为 JSON 返回” - 谁说的?

In fact, that's exactly what you should do.事实上,这正是你应该做的。 In this case, you will want to create an outer class that contains all of the fields that you want.在这种情况下,您需要创建一个包含所有您想要的字段的外部类。 It would look something like this:它看起来像这样:

public class DataResponse {

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

    <relevant getters and setters>
}

And your service code would change to something like this:您的服务代码将更改为如下所示:

@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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM