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

如何将List<Object[]>转换为Angular前端所需指定格式(Spring Boot)

解决Spring Boot接口返回格式适配Angular需求的方案

方案一:使用DTO类映射查询结果(推荐,类型安全)

创建对应前端所需格式的DTO类,让JPA直接将查询结果映射到该类实例:

  1. 定义DTO类
public class ProductCountDTO {
    private String name;
    private Long y;

    // 构造方法参数顺序需与SQL查询结果列顺序完全一致
    public ProductCountDTO(Long y, String name) {
        this.y = y;
        this.name = name;
    }

    // 生成getter方法(setter可选,视需求而定)
    public String getName() {
        return name;
    }

    public Long getY() {
        return y;
    }
}
  1. 修改Repository查询方法
    更新@Query的返回类型为List<ProductCountDTO>,确保SQL查询的列顺序与DTO构造方法参数匹配:
@Query(value = "select count(*) , p.des_prod from produit p , pack k ,dis d WHERE p.cod_prod = k.cod_prod and k.cod_dist=d.cd_dist and adresse =:adresse group by p.des_prod", nativeQuery = true)
List<ProductCountDTO> query(@Param("adresse") String adresse);

此时接口返回的JSON格式将直接匹配Angular所需结构。

方案二:Service层手动转换结果

如果不想新增DTO类,可在Service层将List<Object[]>转换为目标格式:

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    public List<Map<String, Object>> getProductCounts(String adresse) {
        List<Object[]> rawData = productRepository.query(adresse);
        return rawData.stream()
                .map(item -> {
                    Map<String, Object> resultMap = new HashMap<>();
                    // 按SQL查询顺序取数,count(*)对应y,des_prod对应name
                    resultMap.put("y", item[0]);
                    resultMap.put("name", item[1]);
                    return resultMap;
                })
                .collect(Collectors.toList());
    }
}

Controller调用该Service方法返回结果即可,前端收到的JSON会是预期的对象数组格式。


内容的提问来源于stack exchange,提问作者Mariem KAROUI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:36:14