java 发送请求和复杂json的解析。

String add_url = "http://127.0.0.1:8080/test/doThis";  
   URL url = new URL(add_url);  
   HttpURLConnection connection = (HttpURLConnection)url.openConnection();  
   connection.setDoInput(true);  
   connection.setDoOutput(true);  
   connection.setRequestMethod("POST");  
   connection.setUseCaches(false);  
   connection.setInstanceFollowRedirects(true);  
   connection.setRequestProperty("Content-Type","application/json");  
   connection.connect();  
   DataOutputStream out = new DataOutputStream(connection.getOutputStream());  
   JSONObject obj = new JSONObject();  

   obj.put("code", -1002);       
   obj.put("message", "msg");  
   out.writeBytes(obj.toString());  
   out.flush();  
   out.close();  
var json_data={
              "name" : "demographics",
              "params" : [1 , 2, 3],
              "items" : [ {"name" : "中文", "value" : 10 }, 
                          {"name": "item2",  "value" : 20 }
                        ]
           };
        $.ajax({
        url : 'chart/graphics',
        type : 'post',
        data : JSON.stringify(json_data),
        contentType : 'application/json;charset=utf-8'   //中文需要加上charset=utf-8才正确
     });

后端写法

   @RequestMapping(value="/{name}", method=RequestMethod.POST, produces="application/json;charset=utf-8;")
    @ResponseBody
    public String postDashboardItem( 
            @PathVariable(value="name")  String name,
            @RequestBody  String params, 

             Model model) {

      JSONObject object= JSON.parseObject(params);

     //do somthings

     return "";  //json string

}

你可能感兴趣的:(java 发送请求和复杂json的解析。)