结论:解决VO类属性与要返回的json串字段名称不一样的问题,需要用到@JsonProperty(“xxx”)这个注解
那具体怎么使用呢?下面我拿我个人的例子来说明。
但可以明显看到,有两个名称一样的name字段。会让人容易混淆。
所以在VO类,我们具体的来写,如:categoryName,productNam。这样写,就可以达到见名知意的效果。
那么问题来了,你这样写VO类的属性,返回的json串字段,也会是categoryName,productNam。
这样就会与我们想要返回的两个name字段不一致。
那么在不改json串两个name名称的情况下,如何达到categotyName在转json的串的时候是name呢?
这就要用到@JsonProperty("name")。
在VO类的categoryName属性上面加上@JsonProperty("name")注解。
这样做,就会将VO类的categoryName属性在转json串的时候,字段名称不会是CategotyName,而是注解中的name。
这样,会与要求返回的name是一样的了,前端可以接收到相应的数据,而VO类属性,也能达到见名知意效果。
(这边只是返回json字段名,并没有加真实数据,单纯为了验证json串格式)
/** * 买家商品 * Created by 李柏霖 * 2020/10/17 20:11 */ package com.lbl.controller; import com.lbl.VO.ProductInfoVO; import com.lbl.VO.ProductVO; import com.lbl.VO.ResultVO; import com.lbl.dataObject.ProductCategory; import com.lbl.dataObject.ProductInfo; import com.lbl.service.ICategoryService; import com.lbl.service.IProductService; 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; @RestController @RequestMapping("/buyer/product") public class BuyerProductController { @Autowired IProductService productService; @Autowired ICategoryService categoryService; @GetMapping("/list") public ResultVO list(){ //1.查询所有的上架商品 List<ProductInfo> productInfoList = productService.findUpAll(); //2.查询类目(一次性查询) List<ProductCategory> categoryList = new ArrayList<>(); //3.数据拼装 //最外层(1层) ResultVO<Object> resultVO = new ResultVO<>(); resultVO.setCode(0); resultVO.setMsg("成功"); //类目层(2层) ProductVO productVO = new ProductVO(); //商品详情层(3层) List<ProductInfoVO> productInfoVOList=new ArrayList<>(); ProductInfoVO productInfoVO = new ProductInfoVO(); productInfoVOList.add(productInfoVO); //在1层拼接2层 resultVO.setData(productVO); //在类(在2层拼接3层) productVO.setProductInfoVOList(productInfoVOList); return resultVO; } }(这边只是返回json字段名,并没有加真实数据,单纯为了验证json串格式)