Spring REST service: retrieving JSON from Request

后端 未结 11 658
甜味超标
甜味超标 2020-11-27 04:35

I am building a REST service on Spring 3.1. I am using @EnableWebMVC annotation for that. Since my service will only be accepting JSON requests, I would also like to dump th

11条回答
  •  庸人自扰
    2020-11-27 04:42

    One simple way to do this would be to get the request body as String and then parse as a Java object. You can use this String then as you want.

    So in your example:

    @RequestMapping(method = RequestMethod.POST, consumes="application/json", produces="application/json", value = "employee")
    @ResponseBody
    public String updateEntity(@RequestBody String empAsString) {
    
        // Do whatever with the json as String 
        System.out.println(empAsString);
    
        // Transform it into the Java Object you want
        ObjectMapper mapper = new ObjectMapper();
        Employee emp = mapper.readValue(empAsString, Employee.class);
    
        // Do some DB Stuff. Anyway, the control flow does not reach this place.
        return "Employee " + emp.getName() + " updated successfully!";
    }
    

    As a note, if you need it as a list you can use:

    List eventsList =
                    mapper.readValue(jsonInString, mapper.getTypeFactory().constructCollectionType(List.class, Employee.class));
    

提交回复
热议问题