JSON 遍历转为Model Bean

时间:2022-11-29 07:30:41
@RequestMapping(value = "/batchAddPageIndexBrand")
        @ResponseBody
        public HashMap<String, Object> batchAddPageIndexBrand(HttpServletRequest request,HttpServletResponse response){
            String userId = request.getSession().getAttribute("userId").toString();
            HashMap<String, Object> mapRes = new HashMap<String, Object>();
            List<PageIndexBrand> pageIndexBrandList=new ArrayList<PageIndexBrand>();
            String jsonStr=request.getParameter("json");
            if(StringUtils.isEmpty(jsonStr)){
                mapRes.put("code", -1);
                mapRes.put("msg","没有要操作的数据");
                return mapRes;
            }
         //将JSON字符串转为JSON数组 
            JSONArray json= JSONArray.fromObject(jsonStr);
            if(json==null || json.size()==0){
                mapRes.put("code", -1);
                mapRes.put("msg","没有要操作的数据");
                return mapRes;
            }
               //遍历JSON数组
            for(int i=0;i<json.size();i++){
              //获取JSON对象
                 JSONObject object = (JSONObject)json.get(i);
             //将JSON对象转为ModelBean
                 PageIndexBrand pageIndexBrand = (PageIndexBrand)JSONObject.toBean(object,PageIndexBrand.class);
                  if(pageIndexBrand != null){
                      pageIndexBrand.setAddUserId(Integer.parseInt(userId));
                      pageIndexBrand.setAddTime(StringUtil.returnDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"));
                      pageIndexBrand.setEditTime(StringUtil.returnDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"));
                      pageIndexBrand.setEditUserId(Integer.parseInt(userId));
                      pageIndexBrandList.add(pageIndexBrand);
                  }
            }
            ServiceMessage<?> res=pageIndexBrandService.batchOperateIndexBrand(pageIndexBrandList);
            if(res.getStatus().getCode().equals("0")){
                mapRes.put("code", 0);
                mapRes.put("msg", "ok");
            }else{
                mapRes.put("code", -1);
                mapRes.put("msg",res.getMessage());
            }
            return mapRes;
        }