How deserialize JSON object from HttpResponse using Jackson annotations?

MebAlone picture MebAlone · Aug 5, 2011 · Viewed 45.8k times · Source

I'm using the Apache http classes to call a web service that returns a JSON object in the response body. I have a Jackson annotated java class mapped to the JSON object. I want to do something this, but google hasn't turned up the correct boilerplate.

    String url = hostName + uri;
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpGet);
    MyObject myObject = (MyObject)response.getEntity().getContent();

Answer

Bozho picture Bozho · Aug 5, 2011

You have to use the ObjectMapper:

MyObject myObject = objectMapper.readValue(response.getEntity().getContent(), MyObject.class);

(An object mapper instance can be reused, so no need to create a new one for each deserialization)