Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How deserialize JSON object from HttpResponse using Jackson annotations?

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(); 
like image 963
MebAlone Avatar asked Aug 04 '11 22:08

MebAlone


People also ask

How does Jackson deserialize dates from JSON?

How to deserialize Date from JSON using Jackson. In order to correct deserialize a Date field, you need to do two things: 1) Create a custom deserializer by extending StdDeserializer<T> class and override its deserialize(JsonParser jsonparser, DeserializationContext context) method.

How does Jackson convert object to JSON?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

What is Jackson deserialization?

Jackson is a powerful and efficient Java library that handles the serialization and deserialization of Java objects and their JSON representations. It's one of the most widely used libraries for this task, and runs under the hood of many other frameworks.


1 Answers

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)

like image 176
Bozho Avatar answered Sep 19 '22 19:09

Bozho