一定要有 Jackson 的jar包依赖,就算有了fastjson,也要有Jackson包
com.fasterxml.jackson.core
jackson-databind
2.9.8
com.fasterxml.jackson.core
jackson-core
2.9.8
com.fasterxml.jackson.core
jackson-annotations
2.9.8
前端传来的是json数据不多时:[id:id],可以直接用@RequestParam来获取值
@Autowired
private AccomodationService accomodationService;
@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestParam ("id") int id) {
int res=accomodationService.deleteData(id);
return "success";
}
前端传来的是一个json对象时:{【id,name】},可以用实体类直接进行自动绑定
@Autowired
private AccomodationService accomodationService;
@RequestMapping(value = "/add")
@ResponseBody
public String addObj(@RequestBody Accomodation accomodation) {
this.accomodationService.insert(accomodation);
return "success";
}
前端传来的是一个json对象时:{【id,name】},可以用Map来获取
@Autowired
private AccomodationService accomodationService;
@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestBody Map map) {
if(map.containsKey("id"){
Integer id = Integer.parseInt(map.get("id"));
}
if(map.containsKey("name"){
String objname = map.get("name").toString();
}
// 操作 ...
return "success";
}
当前端传来这样一个json数组:[{id,name},{id,name},{id,name},...]时,用List
@Autowired
private AccomodationService accomodationService;
@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestBody List list) {
for(Accomodation accomodation:list){
System.out.println(accomodation.toString());
}
return "success";
}
在 $.ajax 中添加 contentType:'application/json' ,让前后端传递的编码一致
用 JSON.stringify() 把 json 对象变成 json 字符串传给后端
ajax默认为 application/x-www-form-urlencoded; charset=UTF-8 ,要穿json数据就不能用默认值
$.ajax({
type: "post",
url: "",
contentType:'application/json', //改为json的编码
data: JSON.stringify(data.field), //传递时把json对象,变成json字符串
dataType: "json", //处理返回的json数据
success: function(data){
JSON.parse(data) //把后端传递的json字符串转为json对象
}
});
处理后端传递的json数据时用 JSON.parse() 把 json 字符串转为 json 对象
后端使用 SpringMVC 向前端传 json 时 必须有注解 @RequestBody
有了Jackson后可以直接传对象,输出时是json数据(里面的数据就是对象里面的值)
@RequestMapping("/postList")
@ResponseBody
public User postList(User user){
System.out.println(user);
return user;
}
或者在类上面加 @RestController
@RestController
public class Controller {
@RequestMapping("/postList")
public User postList(User user){
System.out.println(user);
return user;
}
}
参考文档:https://www.cnblogs.com/zzsuje/articles/10329948.html