-1

I have an api with given request body and response , now I have to call restTemplate for it and get particular response from it

This is my requestBody ->

{"ids":["MS8B50FHS"]}

And this is my response ->

{
    "status": 200,
    "success": true,
    "message": "detail found!",
    "data": {
        "MS8B50FHS": {
            "ids": "MS8B50FHS",
            "creditTerm": "Credit 45 days"
        }
    }
}

Now for this I need to get creditterm by calling a restTemplate

@Override
        public String findByUniqueSupplierId (String ids){
            final String url = BaseUrl ;
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<Object> requestEntity = new HttpEntity<>(headers);
            Map<String, List<String>> params = new HashMap<>();
            params.put("ids", Collections.singletonList(ids));
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> object = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class , params);
            return object.getBody();
        }

I was trying something like this but not getting result

Java_Guy
  • 1
  • 1

1 Answers1

0

You can assign JSON data to objects using the fromJson() method from the Gson library.

    String body = object.getBody();
    Gson gson = new Gson();
    Map<String, Object> map = gson.fromJson(body, HashMap.class);
    Map<String, Object> data = (Map<String, Object>) map.get("data");
    Map<String, Object> creditTerm = (Map<String, Object>) data.get("MS8B50FHS");
    String creditTermValue = creditTerm.get("creditTerm").toString();
    System.out.println(creditTermValue);

Could be refactored.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
bjorke07
  • 94
  • 1
  • 10