使用注解@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數據格式化):

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM