The front end passes JSON array data to the back end (parsing method)

When passing an array         between the front end and the back end , due to the limitations of the HTTP protocol, parameters of the array type cannot be directly passed.
Request parameters need to be converted to string format and passed to the backend, so the gradeIdArray array needs to be converted into a JSON string through the JSON.stringify() method, and passed to the backend as a parameter.

add(){
      // 将选中的权限等级的 ID 转换为整数类型,并存储在一个数组中
      let gradeIdArray = []
      for (let i = 0; i < this.selectGradeArray.length; i++) {
        gradeIdArray.push(parseInt(this.selectGradeArray[i]))
      }
      // 发送 POST 请求,将角色名称和权限等级的 ID 数组传递给后台
      axios.post('/project/role/add', {
          roleName: this.addObj.name,
          gradeIdArray: JSON.stringify(gradeIdArray)
      }).then(resp => {
        if (resp.data === 'ok') {
          alert('添加成功')
          // 清空
          this.addObj.name = ''
          this.selectGradeArray = []
        } else {
          alert('添加失败')
        }
    });
  }

        In the back-end controller method, you need to use the @RequestBody annotation to receive the JSON data passed by the front-end and convert it into a corresponding Java object

  @PostMapping("add")
    public String add(@RequestBody Map<String, Object> params) {
        String roleName = (String) params.get("roleName");
        String gradeIdArrayJson = (String) params.get("gradeIdArray");
        ObjectMapper mapper = new ObjectMapper();
        List<Integer> gradeIdList = null;
        try {
            gradeIdList = mapper.readValue(gradeIdArrayJson, new TypeReference<List<Integer>>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        roleService.add(roleName, gradeIdList.toArray(new Integer[0]));
        return "ok";
    }

        Use the @RequestBody annotation to receive the JSON data passed by the front end, and use the ObjectMapper object in the Jackson library to convert it into a List<Integer> object.

        During conversion, use the TypeReference class to specify the target type of conversion as List<Integer>.

        Then, convert the converted List<Integer> object into an Integer array, and pass it to the roleService.add() method for processing.

Guess you like

Origin blog.csdn.net/m0_74421344/article/details/130919730