1. 程式人生 > >springmvc接收json資料的4種方式

springmvc接收json資料的4種方式

ajax我經常用到,傳的資料是json資料,json資料又有物件,陣列。所有總結下springmvc獲取前端傳來的json資料方式:

1、以RequestParam接收

前端傳來的是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";
}

 

2、以實體類方式接收

前端傳來的是一個json物件時:{【id,name】},可以用實體類直接進行自動繫結

@Autowired
private AccomodationService accomodationService;

    @RequestMapping(value = "/add")
    @ResponseBody
    public String addObj(@RequestBody Accomodation accomodation) {
        this.accomodationService.insert(accomodation);
        return "success";
    }

3、以Map接收

 

前端傳來的是一個json物件時:{【id,name】},可以用Map來獲取

@Autowired
private AccomodationService accomodationService;

@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestBody Map<String, String> map) {
    if(map.containsKey("id"){
        Integer id = Integer.parseInt(map.get("id"));
    }
    if(map.containsKey("name"){
        String objname = map.get("name").toString();
    }
    // 操作 ...
    return "success";
}

 

4、以List接收

當前端傳來這樣一個json陣列:[{id,name},{id,name},{id,name},...]時,用List<E>接收

 

@Autowired
private AccomodationService accomodationService;

@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestBody List<Accomodation> list) {
    for(Accomodation accomodation:list){
        System.out.println(accomodation.toString());
    }
    return "success";
}