Wednesday, March 5, 2014

Jackson deserialization in controller

Here is an example for deserialize JSON data from string placed in the body of the request.

Here are clear (not-working) and work-around.

Workaround:


    @RequestMapping(
        value = "/add_venue_raw",
//        method = RequestMethod.POST, // if you like
        produces="application/json",
        consumes={"application/json"}
    )
    @ResponseBody
    public String addVenueRaw( @RequestBody String body ) throws IOException {
        log.info( "received body: " + body );


        ObjectMapper mapper = new ObjectMapper();
        Venue x = mapper.readValue( body, Venue.class );
        log.info( "obj.toString() = " + x.toString() );


        return "{\"status\":\"no warnings
\"}";
    }


Clear but not working way

    @RequestMapping(
        value = "/add_venue_buggy",
        method = RequestMethod.POST,
        consumes={"application/json"},
//        produces="application/json;charset=utf-8"
        produces="application/json"
    )
    @ResponseBody
    public String addVenue( @RequestBody VenuePhoto venue ) {
// this DO NOT works!!!!!!!!!!!!!!!!!!!!
        return "{}";
    }

   


Deserialize as map

Deserialize body data as map and return the same body (useful for tests):
    @RequestMapping(
        value = "/add_venue_raw",
//        method = RequestMethod.POST,
        produces="application/json",
        consumes={"application/json"}
    )
    @ResponseBody
    public String addVenueRaw( @RequestBody String body ) throws IOException {

        log.info( "received body: " + body );
       
        Map<String, String> map = new HashMap<String, String>();
        ObjectMapper mapper = new ObjectMapper();

        try {
            //convert JSON string to Map
            map = mapper.readValue(body,
                new TypeReference<HashMap<String, String>>() {
                });


            System.out.println(map);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return map.toString();
    }


No comments:

Post a Comment