Solve the Problem of parseerror when spring mvc returns json data to ajax. jsonparseerror
Recently, when ajax is used to receive json data transmitted by spring mvc, A parseerror error always occurs. The error source code is as follows:
Front end:
$. Ajax ({type: 'post', url: "groupFunctionEdit", dataType: 'json', contentType: "application/json", data: json. stringify (functiondata), success: function (data) {alert ('data loaded successfully' + data. msg) ;}, error: function (xhr, type) {alert ('data loading failed'); console. log (type );}
Background Controller:
@RequestMapping("/groupFunctionEdit") public @ResponseBody Object groupFunctionEdit(@RequestBody List<YyGroupFunction> yyGroupFunctionList) throws JsonProcessingException{ return "success"; }
You can find the following answers:
When a simple type is used to receive data, such as String, the annotation @ RequestBody is not required.
Here we need to use spring mvc to process the json dependent jar package: jackson. databind. jar
Solution:
The front-end does not need to be modified. In the background, map the required data and convert it to the String type:
@RequestMapping("/groupFunctionEdit") public @ResponseBody Object groupFunctionEdit(@RequestBody List<YyGroupFunction> yyGroupFunctionList) throws JsonProcessingException{ Map<String,Object> map = new HashMap<String,Object>(); map.put("msg", "success"); ObjectMapper mapper = new ObjectMapper(); String msg = mapper.writeValueAsString(map); return msg; }
The data uploaded to the front-end becomes:
{"msg":"success"}
You can use jQuery to resolve the issue and no error will be reported.
The above section describes how to solve the parseerror problem when spring mvc returns json data to ajax. I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!