❤️参数post以json字符串传输对象和集合

小明的学习圈子2023-08-03后端前后端交互

一、参数post传输json字符串,对象和集合

1、axios封装的psot方法

//post
export function postAction(url,parameter) {
  let header = {"token":"123456"};
  return axios({
    url: url,
    method:'post' ,
    data: parameter,
    headers: header
  })
}

2、调用后端方法

let jsonData = {
       
      name: '5',
      id: '6',
      list: [
        {
          name: '001',
          id: '12345687'
        },
        {
          name: '1',
          id: '12345687das'
        }
      ]
    }
    postAction('/test/invoker', { jsonData: JSON.stringify(jsonData) }).then(res => {
      let result = res
      alert(1)
    })

3、后端controller

@RestController
@RequestMapping("/test")
public class TestController  {
    @Autowired
    private IMainService mainService;

    @PostMapping(value = "/invoker")
    public Result<?> invoker(@RequestBody String jsonData) {

        boolean result = mainService.test(jsonData);
        if (result) {
            return Result.ok();
        }
        return Result.error("更新失败!");
    }

}

4、后端service


@Service
public class MainServiceImpl extends ServiceImpl<MainMapper, Main> implements IMainService {

    @Autowired
    private ISubService subService;
    @Transactional
    @Override
    public boolean test(String jsonData) {
        if(StringUtils.isBlank(jsonData.trim())){
            return false;
        }
        Main main = new Main();
        String strReceiveJson = jsonData;
        JSONObject jsonObject = JSONObject.parseObject(strReceiveJson);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义新的日期格式
        JSONObject result = jsonObject.getJSONObject("jsonData");
        JSONArray jsonArray = JSONObject.parseObject(result.toString()).getJSONArray("list");
        List<Sub> sublist = JSONObject.parseArray(jsonArray.toJSONString(), Sub.class);
        boolean mainResult = true;
        boolean subResult = true;
        try {
            if (result.containsKey("trainOrderNo") && StringUtils.isNotBlank(result.get("trainOrderNo").toString())) {
                main.setTrainOrderNo(result.get("trainOrderNo").toString()); 
            }
       
            if (result.containsKey("orderDate") && StringUtils.isNotBlank(result.get("orderDate").toString())) {

                main.setOrderDate(formatter.parse(result.get("orderDate").toString()));    
            }
           
        } catch (ParseException e) {
            e.printStackTrace();
        }

        mainResult = this.saveOrUpdate(main);
        if (!CollectionUtils.isEmpty(sublist) && sublist.size() > 0) {
            subResult = subService.saveOrUpdateBatch(sublist);
        }


        return mainResult && subResult;
    }
}

5、对象json转换

    public boolean test(String jsonData) {

        if (StringUtils.isBlank(jsonData.trim())) {
            return false;
        }
        String strReceiveJson = jsonData;
        JSONObject jsonObject = JSONObject.parseObject(strReceiveJson);
        JSONObject result = jsonObject.getJSONObject("jsonData");
        Plan plan = result.toJavaObject(Plan.class);

        return this.saveOrUpdate(plan);
    }

二、map接收

1、前端

      let form = { resultList: [], companyInfo: formData }
      that.verifyUrl = '/test/verifyBatch'
      postAction(that.verifyUrl, form)
        .then(res => {
          if (res.success) {
            that.$message.success(res.message)
            that.$emit('ok')
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.loadData()
        })

2、controller接收

    public Result<String> verifyBatch(@RequestBody Map<String, Object> map) {

        boolean result = companyInfoService.verifyBatch(map);
        if (result) {
            return Result.OK("成功!");
        } else {
            return Result.error("失败!");
        }
    }

3、service

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
public boolean verifyBatch(Map<String, Object> map) {

        CompanyInfo companyInfo = JSON.parseObject(JSON.toJSONString(map.get("companyInfo")), CompanyInfo.class);

        List<RecordSingleChannel> resultList = JSONArray.parseArray(JSONArray.toJSONString(map.get("resultList")), RecordSingleChannel.class);

        companyInfo.setUpdateDate(new Date());
        boolean singleResult = this.updateById(companyInfo);
        boolean result = true;
        List<RecordSingleChannel> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(resultList) && resultList.size() > 0) {
            recordSingleChannelService.removeById(companyInfo.getId());
            for (RecordSingleChannel recordSingleChannelInfo : resultList) {
                recordSingleChannelInfo.setCreateDate(new Date());
                recordSingleChannelInfo.setUpdateDate(new Date());
                list.add(recordSingleChannelInfo);
            }
            result = recordSingleChannelService.saveBatch(list);
        }

        return singleResult && result;
    }
Last Updated 2024/4/6 11:55:17