Home > Back-end >  How to handle dynamic REST API response in with Spring's RestClient
How to handle dynamic REST API response in with Spring's RestClient

Time:08-01

I am consuming EtherScan REST API which gives dynamic response based on requested Parameters Basically 2 different response types wiz.

{ 
  "status" = 1,
  "message" = "OK",
  "result" = "..some string.."
}

and

{ 
  "status" = 1,
  "message" = "OK",
  "result" = [{..},{..}...]
}

I am trying to handle it via single model which is

class APIResponseModel
{
@Getter
@Setter
int status; 
string message;
Object result;
}

My method to get API response look like this

APIResponseModel responseModel = restTemplate.getForObject(API_ENDPOINT_URL, APIResponseModel.class );

But at runtime it gives me error because of changing response type. Is there any better way to handle dynamic API response ?

CodePudding user response:

You need nested Pojo following is example

   "data": [
{
    "id": 11881,
    "date": "2018-03-26T16:22:08",
    "date_gmt": "2018-03-26T14:22:08",
    "guid": {
        "rendered": "http://google.com"
    },
    "modified": "2018-03-26T16:22:08",
    "modified_gmt": "2018-03-26T14:22:08",
    "slug": "some text",
    "status": "some status",
    "type": "post",
    "link": "http://google.com",
    "title": {
        "rendered": "some title"
    }
 }
]

   public class Response{
     private List<Post> data;
   }

public class Post{
   private String id;
   private String date;
   private String date_gmt;
   private String guid;
  }

Also use json Ignore so if pojo null will remove from response

CodePudding user response:

I assume that your example should be a JSON format response. JSON uses ":" instead of "=".

To handle dynamic REST API response in JSON format, use Jackson.

String response = restTemplate.getForObject(API_ENDPOINT_URL, String.class);
JsonNode root = new ObjectMapper().readTree(response);
JsonNode result = root.get("result");
if (result.isTextual()) {
    :
} else if (result.isArray()) {
    :
}
  • Related