37

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();
1

1 Answer 1

79

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)

Sign up to request clarification or add additional context in comments.

3 Comments

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)
Getting "Non-static method 'readValue(java.io.InputStream, java.lang.Class<T>)' cannot be referenced from a static context"
Wow I'm a noob I just had to do ObjectMapper objectMapper = new ObjectMapper(); first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.