spring boot 接收Json、List入参,List转JSONArray和JSONArray转List

本文章调用的是阿里的 fastjson对象

前端直接传入数组(这种方式最简单):

    [{"id":1,"userId":1512629135717411,"plate":"3D展览","customPlate":"3D展览","state":1,"sort":1},{"id":2,"userId":1512629135717411,"plate":"作品","customPlate":"作品","state":1,"sort":2},{"id":3,"userId":1512629135717411,"plate":"出售中","customPlate":"出售中","state":0,"sort":3},{"id":4,"userId":1512629135717411,"plate":"活动/展览","customPlate":"活动/展览","state":0,"sort":5},{"id":5,"userId":1512629135717411,"plate":"赞过的","customPlate":"赞过的","state":0,"sort":6},{"id":6,"userId":1512629135717411,"plate":"简介","customPlate":"简介","state":1,"sort":7}]

后端用N种方式接收数组,我这里使用JSONArray对象接收,然后再进行调用toJavaList的方法转为List

上面只是叙述阿里的 fastjson对象接收前端传来的数组方式,大家可以直接用List list接收

@RequestMapping(value = SORT, method = RequestMethod.PUT)
public Result customNavigationSort(@RequestBody JSONArray jsonParam) {
    List customNavigationList = jsonParam.toJavaList(CustomNavigation.class);
    return customNavigationService.customNavigationSort(customNavigationList);
}

 

-------------------------------------------  分割线   -------------------------------------------------------

前端传入数组格式为对象方式的数组(这种方式传参,后端需要处理好对应的转换,否则会报错)

{
    "customNavigationList":
        [{"id":1,"userId":1512629135717411,"plate":"3D展览","customPlate":"3D展览","state":1,"sort":1},{"id":2,"userId":1512629135717411,"plate":"作品","customPlate":"作品","state":1,"sort":2},{"id":3,"userId":1512629135717411,"plate":"出售中","customPlate":"出售中","state":0,"sort":3},{"id":4,"userId":1512629135717411,"plate":"活动/展览","customPlate":"活动/展览","state":0,"sort":5},{"id":5,"userId":1512629135717411,"plate":"赞过的","customPlate":"赞过的","state":0,"sort":6},{"id":6,"userId":1512629135717411,"plate":"简介","customPlate":"简介","state":1,"sort":7}]
}

后端用JSONObject对象接收, 再用JSONArray转List的方式转换

@RequestMapping(value = SORT, method = RequestMethod.PUT)
public Result customNavigationSort(@RequestBody JSONObject jsonParam) {
    JSONArray array = jsonParam.getJSONArray("customNavigationList");
    List customNavigationList = JSONObject.parseArray(array.toJSONString(), CustomNavigation.class);
    return customNavigationService.customNavigationSort(customNavigationList);

}

 

你可能感兴趣的:(java,fastJson)