35

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();
skaffman
  • 398,947
  • 96
  • 818
  • 769
MebAlone
  • 547
  • 1
  • 5
  • 11

1 Answers1

77

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)

Eric
  • 6,563
  • 5
  • 42
  • 66
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • All Jackson methods have form 'readValue(source, type)', so it kind of follows pattern. And when using IDE, auto-completion helps a lot showing possibilities (if not, need to check javadocs) – StaxMan Aug 05 '11 at 23:29
  • Getting "Non-static method 'readValue(java.io.InputStream, java.lang.Class)' cannot be referenced from a static context" – Collin Jan 19 '23 at 17:05
  • Wow I'm a noob I just had to do `ObjectMapper objectMapper = new ObjectMapper();` first – Collin Jan 19 '23 at 17:08