首页 > 解决方案 > Springboot - 如何在 JSON 响应中命名响应数组和对象

问题描述

我有带有控制器的 Springboot REST API 应用程序,例如:

@GetMapping()
public List<CarResponse> getCars() {
    List<CarResponse> cars= carService.getCars();
    return cars;
}

我的 CarResponse 看起来像:

public class CarResponse {
    private int id;
    private String type;
    private String model;
}

这工作正常;但是,返回的 JSON 包含一个匿名 JSON 对象的 JSON 匿名数组,例如:

[
    {
        "id": 1,
        "type": "SUV",
        "model": "Toyota"
    },
    {
        "id": 2,
        "type": "SPORT",
        "model": "Porsche"
    },
    ...
]

如何获得由命名数组和对象组成的响应,以便响应 JSON 看起来像

{
    "cars": [
            "car": {
                "id": 1,
                "type": "SUV",
                "model": "Toyota"
            },
            "car": {
                "id": 2,
                "type": "SPORT",
                "model": "Porsche"
            },
            ...
    ]
}

标签: jsonspring-bootrest

解决方案


推荐阅读