You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot接口如何返回嵌套data结构的JSON格式?

解决Spring Boot接口返回JSON格式不符问题

你的问题核心是返回的JSON中data字段直接对应数组,而期望的是data字段对应一个包含data数组的对象。只需对返回数据做一层嵌套包装即可解决,下面提供两种实现方式:

方法一:用Map嵌套快速修改

直接在现有代码基础上,把info.getList()包装到一个新的Map中,再赋值给外层data:

@RequestMapping(value = "list", method = RequestMethod.GET)
@ResponseBody
public Map<String,Object> getPropertyList(@RequestParam(defaultValue= "1") int pageNumber, @RequestParam(defaultValue= "5") int pageSize) {
    Map<String,Object> map = new HashMap<>();
    PageHelper.startPage(pageNumber, pageSize, true);
    List<Property> propertyList = propertyService.queryList();
    PageInfo<Property> info = new PageInfo<>(propertyList);
    
    map.put("code","200");
    map.put("msg","success");
    
    // 新增:创建内层Map包装列表
    Map<String, Object> innerData = new HashMap<>();
    innerData.put("data", info.getList());
    map.put("data", innerData); // 将内层Map赋值给外层data
    
    return map;
}

方法二:定义统一响应实体类(推荐)

为了更规范和复用,建议定义一个统一的API响应实体类,避免每次手动拼接Map:

1. 创建响应实体类

public class ApiResponse<T> {
    private String code;
    private String msg;
    private DataWrapper<T> data;

    // 全参/无参构造方法
    // getter和setter方法

    public static class DataWrapper<T> {
        private List<T> data;

        // 构造方法
        // getter和setter方法
    }
}

2. 修改控制器方法

@RequestMapping(value = "list", method = RequestMethod.GET)
@ResponseBody
public ApiResponse<Property> getPropertyList(@RequestParam(defaultValue= "1") int pageNumber, @RequestParam(defaultValue= "5") int pageSize) {
    PageHelper.startPage(pageNumber, pageSize, true);
    List<Property> propertyList = propertyService.queryList();
    PageInfo<Property> info = new PageInfo<>(propertyList);
    
    ApiResponse<Property> response = new ApiResponse<>();
    response.setCode("200");
    response.setMsg("success");
    
    ApiResponse.DataWrapper<Property> dataWrapper = new ApiResponse.DataWrapper<>();
    dataWrapper.setData(info.getList());
    response.setData(dataWrapper);
    
    return response;
}

两种方法都能让你得到预期的JSON格式:

{
    "code": "200",
    "msg": "success",
    "data": {
        "data": []
    }
}

内容的提问来源于stack exchange,提问作者wen tian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 19:55:50