Sachin Mukherjee
Sachin Mukherjee

Reputation: 51

How to unmarshall a ReponseEntity Object returned by RestTemplate?

I have two third party API's which I'm hitting and getting the response as ResponseEntity<Object> using RestTemplate. I want to unmarshal the response into objects so that I can access the content inside of it.

ResponseEntity<Object> response = restTemplate.exchange(apiEndPointToHit,HttpMethod.GET,null,Object.class);

1st API Response

    {
        "responseStatus": "SUCCESS",
        "size": 88,
        "start": 0,
        "limit": 200,
        "sort": "id asc",
        "users": [
            {
                "user": {
                    "user_name": "XYZ",
                    "user_first_name": "XYZ",
                    "user_last_name: "XYZ",
                    "user_email": "XYZ",
                  }
            },

           {
                "user":{
                   "user_name":"ABC",
                   "user_first_name":"ABC",
                   "user_last_name":"ABC",
                 },
             },

             {
               "user":{
                   "user_name":"PQR",
                   "user_first_name":"PQR",
                   "user_last_name":"PQR",
                }
             },

           }
         ]
    }

In this response, users will contain multiple user. I want to get list of all user. So that I can access the content of each user object inside that list fields like user_name, user_first_name, etc.

2nd API response is

{
  "message": {
    "documents": {
   }
 }
}

In this case, one message will have one document. I want to access the document. JSON responses contain multiple fields. So it is not possible to create a POJO class. Is there any way to access the Objects inside response entity with creating POJO classes?

Upvotes: 0

Views: 355

Answers (1)

TechGeek
TechGeek

Reputation: 508

We can use either Object mapper or JSONObject which helps to deserialize the JSON body. I would suggest to use JSONObject and following the below example to unmarshall jsonbody.

1. Add Dependency

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180130</version>
</dependency>
  1. Initialize the JSONObject passing the jsonReponse from the restTemplate.
JSONObject jo = new JSONObject(jsonResponse);
  1. Try acceessing the objects in jsonResponse by just doing
getJsonObject/getJsonArray

JSONArray ja = jo.getJsonArray("users");

Upvotes: 1

Related Questions