springboot接收Json参数

1.接收map参数:
  参数格式:test3?robitid=000000000133&name=记得撒娇&age=36
    /**
     * map接受参数
     * @param map
     */
    @RequestMapping(value="/test3")
    @ResponseBody
    public void test3(@RequestParam  Map<String,String> map){ //{key:"value",key1:"value1"}
        System.out.println(map);
    }
打印结果:
{robitid=000000000133, name=记得撒娇, age=36}


2.接收 JSONObject 类型参数 再转换成map
  参数格式:{"robitid":"000000000133","name":"记得撒娇","age":"36"}
   /**
     * jsonObject 转 map
     * @param jsonParam
     */
    @RequestMapping(value="/test1")
    @ResponseBody
    public void test1(@RequestBody JSONObject jsonParam){ //{"key":"value","key1":"value1"} 这种格式

        System.out.println(jsonParam);
        Map<String,Object> map =new HashMap<>();
        //开始转换
        Iterator it =jsonParam.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            map.put(entry.getKey(), entry.getValue());
        }

        System.out.println(map);
    }
打印结果:
{"name":"记得撒娇","robitid":"000000000133","age":"36"}
{name=记得撒娇, robitid=000000000133, age=36}


3.接收 JSONArray 
  参数格式:[{"robitid":"000000000133","name":"记得撒娇","age":"36"},{"robitid":"000000000133","name":"撒大苏打","age":"25"}]
   /**
     * jsonArray 转 jsonObject 在转 Map(String,Object)> 最后放入list
     * @param jsonArray
     */
    @CrossOrigin(origins = "*")
    @RequestMapping(value="/test2")
    @ResponseBody
    public void test2(@RequestBody JSONArray jsonArray){ // [{"key":"value","key1":"value1"},{"key":"value","key1":"value1"}] 这种格式
        List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
        System.out.println(jsonArray);
        for(int i=0;i<jsonArray.size();i++){
            Map<String,Object> map = new HashMap<String, Object>();
            JSONObject jsObject= jsonArray.getJSONObject(i); //JsonArray 转 JsonObject
            Iterator it =jsObject.entrySet().iterator(); //jsonObject 转map
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
                map.put(entry.getKey(), entry.getValue());
            }
            list.add(map);
        }

        System.out.println("---------------------------------------------------------");
        for (int j=0;j<list.size();j++){
            System.out.println(list.get(j));
        }

打印结果:
[{"robitid":"000000000133","name":"记得撒娇","age":"36"},{"robitid":"000000000133","name":"撒大苏打","age":"25"}]
---------------------------------------------------------
{name=记得撒娇, robitid=000000000133, age=36}
{name=撒大苏打, robitid=000000000133, age=25}

你可能感兴趣的:(springboot接收Json参数)