1. The commonly used way to write springMVC to return json format data is to use the @ResponseBody annotation. Add this annotation before each method. The json parsing mechanism of springMVC will automatically convert the return value (Object type object) into json format data. If the returned json object is more complicated, each method needs to define many objects, which will bring a lot of work to development. The following introduces a method, directly use the json object to set the data and put it back.
2. When the following json format data is encountered, if the difference is used in the @ResponseBody method, you need to create multiple Java objects.
{ "total":2, "list":[ { "person":{"name":"eakom0","key":0}, "msg":{"cod":0,"name":"eakom0"} }, { "person":{"name":"eakom1","key":1}, "msg":{"cod":1,"name":"eakom1"} } ], "attachment":{"name":"attachment","version":1}}If you use splicing method, use JsonObject splicing directly without creating an object to return. The code is as follows:
@RequestMapping("returnJson") public void returnJson (HttpServletRequest request, HttpServletResponse response){ JSONObject json = new JSONObject(); json.element("total", 2); List<Map<String,JSONObject>> list=new ArrayList<Map<String,JSONObject>>(); for(int i=0;i<2;i++){ JSONObject person=new JSONObject(); person.element("name", "eakom"+i); person.element("key", i); JSONObject msg=new JSONObject(); msg.element("name", "eakom"+i); msg.element("cod", i); Map<String,JSONObject> map=new HashMap<String,JSONObject>(); map.put("person", person); map.put("msg", msg); list.add(map); } json.element("list", list); JSONObject attachment=new JSONObject(); attachment.element("name", "attachment"); attachment.element("version", 1); json.element("attachment", attachment); responseDatagrid(response, json); } public void responseDatagrid(HttpServletResponse response, JSONObject jObject) { response.setContentType("application/json"); response.setHeader("Cache-Control", "no-store"); try { PrintWriter pw=response.getWriter(); pw.write(jObject.toString()); pw.flush(); } catch (IOException e) { e.printStackTrace(); } }3. Use this to return to json. The structure is not clear when editing the code. It is not a special situation and is not recommended.
The above article springMVC returns complex json format data method is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.