Nishil Nishil - 18 days ago 7
JSON Question

Return JSON Using Map

I have a method, which changes the status from 'Active' to 'InActive' and vice

versa, of a record, by fetching it's id.

Now, I want to convert it to return a ResponseEntity object, inside which, I have a map stored

When I test my method, I get a 400: Bad Request

////////////////////////Old Method////////////////

@RequestMapping("toggleStatus")
public @ResponseBody void toggleStatus(@RequestParam("resourceId") Long resourceId ){
ResourceElementMaster resourceElementMaster = resourceElementService.findById(resourceId);
if(resourceElementMaster.getIsActive() == true) {
resourceElementMaster.setIsActive(false);
} else {
resourceElementMaster.setIsActive(true);
}
resourceElementService.update(resourceElementMaster);
}


//////////////////////New Method/////////////////////////////

@RequestMapping(value="toggleStatus",method=RequestMethod.PUT)
public @ResponseBody ResponseEntity<Map<String, Object>> toggleStatus(@RequestBody Long resourceId ){
Map<String, Object> mapToggle=new HashMap<String, Object>();
ResourceElementMaster resourceElementMaster = resourceElementService.findById(resourceId);
if(resourceElementMaster.getIsActive() == true) {
resourceElementMaster.setIsActive(false);
} else {
resourceElementMaster.setIsActive(true);
}
mapToggle.put("Update",resourceElementService.update(resourceElementMaster));
return new ResponseEntity<Map<String, Object>>(mapToggle, HttpStatus.OK) ;
}


How do I solve this??

N V N V
Answer

Don't pass a json, you only need to pass the resourceId, which you are accepting as a parameter in your method toggleStatus.

Also, use @RequestParam, instead of @RequestBody :

@RequestMapping(value="toggleStatus",method=RequestMethod.POST)
public @ResponseBody ResponseEntity<Map<String, Object>> toggleStatus(@RequestParam(value = "resourceId") Long resourceId ){
    Map<String, Object> mapToggle=new HashMap<String, Object>();
    ResourceElementMaster resourceElementMaster = resourceElementService.findById(resourceId);
    if(resourceElementMaster.getIsActive() == true) {
        resourceElementMaster.setIsActive(false);
    } else {
        resourceElementMaster.setIsActive(true);
    }
    mapToggle.put("Update",resourceElementService.update(resourceElementMaster));
    return new ResponseEntity<Map<String, Object>>(mapToggle, HttpStatus.OK) ;
}
Comments