Spring Boot如何为JSON响应中的数组和返回对象设置自定义名称
首先需要先说明:你给出的目标JSON存在语法错误,JSON数组内不能直接存放"key": value格式的键值对,合法的目标结构如下:
{ "cars": [ { "car": { "id": 1, "type": "SUV", "model": "Toyota" } }, { "car": { "id": 2, "type": "SPORT", "model": "Porsche" } } ] }
以下是两种实现方案:
方案1:自定义包装类实现(推荐,易维护扩展性强)
步骤1:添加单个Car的包装类
用于给每个CarResponse套一层car键:
public class CarWrapper { private CarResponse car; public CarWrapper(CarResponse car) { this.car = car; } // 必须添加getter方法,Jackson序列化需要读取字段 public CarResponse getCar() { return car; } public void setCar(CarResponse car) { this.car = car; } }
步骤2:添加最外层响应包装类
用于给整个数组套一层cars键:
public class CarListResponse { private List<CarWrapper> cars; public CarListResponse(List<CarWrapper> cars) { this.cars = cars; } public List<CarWrapper> getCars() { return cars; } public void setCars(List<CarWrapper> cars) { this.cars = cars; } }
步骤3:修改控制器返回逻辑
@GetMapping() public CarListResponse getCars() { List<CarResponse> rawCars = carService.getCars(); // 逐个包装原始CarResponse List<CarWrapper> wrappedCars = rawCars.stream() .map(CarWrapper::new) .toList(); return new CarListResponse(wrappedCars); }
方案2:用Map快速构造(无需额外定义类,适合临时需求)
直接修改控制器代码即可实现:
@GetMapping() public Map<String, Object> getCars() { List<CarResponse> rawCars = carService.getCars(); // 构造带car键的元素列表 List<Map<String, Object>> wrappedCars = rawCars.stream().map(car -> { Map<String, Object> carMap = new HashMap<>(); carMap.put("car", car); return carMap; }).toList(); // 构造外层响应 Map<String, Object> result = new HashMap<>(); result.put("cars", wrappedCars); return result; }
补充说明:如果你实际不需要每个元素外层的
car键,仅需要外层套一个命名数组,结构如下:{ "cars": [ {"id":1,"type":"SUV","model":"Toyota"}, {"id":2,"type":"SPORT","model":"Porsche"} ] }则不需要定义CarWrapper类,直接在外层包装类中声明
List<CarResponse> cars即可。
另外注意所有POJO类必须添加对应字段的getter方法,否则Jackson序列化会返回空对象。
内容的提问来源于stack exchange,提问作者pixel
相关产品推荐
相关产品推荐

