Spring Boot接口JSON响应多出List外层结构问题排查求助
问题:Spring Boot接口返回JSON带多余外层List包裹,不符合预期
Spring Boot接口返回的JSON响应结构不符合预期:实际返回结果被外层"List"对象包裹数组,但期望直接返回CustomerListingBean对象数组,不清楚多余的List对象来源。
实际返回结果
{"List": [{ "customerNumber": "111", "amount": 75675 }, { "customerNumber": "222", "amount": 30150 }, { "customerNumber": "333", "amount": 120100 }, { "customerNumber": "444", "amount": 50000 }]}
预期返回结果
[{"customerNumber": "111", "amount": 75675}, {"customerNumber": "222", "amount": 30150}, {"customerNumber": "333", "amount": 120100}, { "customerNumber": "444", "amount": 50000}]
相关代码
Controller代码
@PostMapping(path = "/customer-list") public List<CustomerListingBean> getCustomerListing(@RequestBody CustomerListingBean pl) { CustomerListingBean row = new CustomerListingBean(); List<CustomerListingBean> custList = new ArrayList<>(); custList = indCustomerSearchEngine.getCustomerSearchListing(pl.getCustomerNumber()); return custList; }
Service代码
public List getCustomerSearchListing(String customerNumber) { List newList= new ArrayList(); List myList= customerRepository.getInquiryCustomerSearchList( customerNumber ); for (Iterator itr = myList.iterator(); itr.hasNext();) { Object[] col = (Object[]) itr.next(); CustomerListingBean polRow = new CustomerListingBean(); polRow.setCustomerNumber((col[0] != null) ? col[0].toString() : ""); polRow.setAmount((col[1] != null) ? col[1].toString() : ""); newList.add(polRow); return newList; // 注意:此return语句在循环体内,会导致仅返回第一个元素 } }
解决方案
1. 修正Service代码的return语句位置
原Service代码中return newList写在for循环体内,会导致第一次循环就直接返回,无法处理所有数据。需将return语句移到循环体外:
public List<CustomerListingBean> getCustomerSearchListing(String customerNumber) { List<CustomerListingBean> newList= new ArrayList<>(); List<Object[]> myList= customerRepository.getInquiryCustomerSearchList(customerNumber); for (Object[] col : myList) { CustomerListingBean polRow = new CustomerListingBean(); polRow.setCustomerNumber((col[0] != null) ? col[0].toString() : ""); // 若amount是数值类型,避免转成String,建议转成BigDecimal/Long等对应类型 polRow.setAmount((col[1] != null) ? new BigDecimal(col[1].toString()) : BigDecimal.ZERO); newList.add(polRow); } return newList; }
2. 排查全局响应包装逻辑
检查项目中是否存在实现ResponseBodyAdvice的全局响应包装类,这类配置会统一包装所有接口的返回值。如果存在,需修改包装逻辑,或者给当前接口添加排除包装的自定义注解。
3. 检查序列化配置
如果项目使用FastJson等第三方序列化工具,检查配置文件(如application.yml)中是否有将集合序列化为带键对象的设置。例如FastJson配置中若存在WrapRootValue,需移除该配置,避免集合被自动包装。
4. 明确泛型类型
将Service方法的返回值和集合变量都声明为带泛型的List<CustomerListingBean>,避免原始类型导致的序列化类型推断异常。
内容的提问来源于stack exchange,提问作者Newbee
相关产品推荐
相关产品推荐

