使用注解@RestController返回json类型的数据

1.在相应的controller类中添加@RestController

package com.yzy.sell.Controller;

import com.yzy.sell.Entity.ProductCategory;
import com.yzy.sell.Entity.ProductInfo;
import com.yzy.sell.Service.CategoryService;
import com.yzy.sell.Service.ProductService;
import com.yzy.sell.VO.ProductInfoVO;
import com.yzy.sell.VO.ProductVO;
import com.yzy.sell.VO.ResultVO;
import com.yzy.sell.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController //注解@RestController标记在类上,表示该类处理http请求,并且返回json数据
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResultVO list(){
        //1.获取所有的上架商品
        List<ProductInfo> productInfoList = productService.findUpAll();
        //lambda表达式
        List<Integer> categoryTypeLists = productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());
        //2.获取类目(一次性)
        List<ProductCategory> categoryList = categoryService.findByCategoryTypeIn(categoryTypeLists);
        //3.数据拼接
        List<ProductVO> productVOList=new ArrayList<>();
        for(ProductCategory productCategory:categoryList){
            ProductVO productVO=new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());
            List<ProductInfoVO> productInfoVOList=new ArrayList<>();
            for(ProductInfo productInfo:productInfoList){
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfoVO=new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo,productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductList(productInfoVOList);
            productVOList.add(productVO);
        }
        return ResultVOUtil.success(productVOList);
    }
}

2.在页面中查看(安装jsonview的插件即可将json数据格式化):

原文地址:https://www.cnblogs.com/shouyaya/p/13130727.html