415 JSON 解析错误。
可能的原因:没有解析的jar包;JSON 数据格式错误。
pom.xml json jar包
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.2</version> </dependency>
方法一:
$.ajax({ url:"/testJson1", type:"POST", data:{ id:1, name:"name", sn:"sn" }, success:function (result) { $("#dataContainer").html(JSON.stringify(result)); } });
@RequestMapping("/testJson1") @ResponseBody public Book testJson1(Book book){ System.out.println(JSON.toJSONString(book)); return book; }
方法二:
指定contentType:"application/json;charset=UTF-8"
Controller短需指定@RequestBody json数据格式去解析
var data = '{"id":"1", "name": "Brett", "sn":"12" }'; $.ajax({ url:"/testJson3", type:"post", data:data, contentType:"application/json;charset=UTF-8", dataType:"json", success:function (result) { $("#dataContainer").html(JSON.stringify(result)); } });
@RequestMapping("/testJson3") @ResponseBody public String testJson3(@RequestBody Book book){ System.out.println(JSON.toJSONString(book)); return JSON.toJSONString(book); }