Home > Mobile >  How to extract data from JSON response coming from external REST API using RestTemplate in Spring Bo
How to extract data from JSON response coming from external REST API using RestTemplate in Spring Bo

Time:12-14

I am working on spring boot application for consuming external API using RestTemplate.

Below is the service class that I have written to get response from external API:

public String getReportListByClientId(String clientId) {
        ResponseEntity<String> responseEntity = null;
        String jsonResponse = null;
        try {
            final String uri = "https://chapi.cloudhealthtech.com/olap_reports/custom?client_api_id=" clientId;
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders header = new HttpHeaders();
            header.set(HttpHeaders.AUTHORIZATION, "Bearer " apiKey);
            header.set(HttpHeaders.ACCEPT, "application/json");
            
            HttpEntity<String> requestEntity = new HttpEntity<String>("body",header);
            responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
            
            jsonResponse =  responseEntity.getBody();   
        } catch (Exception e) {
            e.printStackTrace();
        }
    return jsonResponse;
}

The following is the response that I am getting using exchange() method:

{
    "links": {
        "RCDSO - Production Environment Cost": {
            "href": "href 1"
        },
        "RCDSO - Development & UAT Environment Cost": {
            "href": "href 2"
        },
        "RCDSO - Total Cost for Prod - Compugen Managed": {
            "href": "href 3"
        },
        "RCDSO - Virtual Machine Cost": {
            "href": "href 4"
        },
        "RCDSO - Azure File Storage Cost": {
            "href": "href 5"
        },
        "RCDSO - Azure Backup and Site Recovery": {
            "href": "href 6"
        },
        "RCDSO - Azure App Services Cost": {
            "href": "href 7"
        }
    }
}

So now, before sending response to client side in my application. I want to fetch data from this response and want to do some manipulation and convert that into custom POJO class. I tried using JSONObject but got some exceptions.

I want to display this JSON data in HTML table using AJAX.

So how should I extract or get individual data from above JSON?

CodePudding user response:

Based on the JSON structure, let's assume you have the following POJOs:

public class Report implements Serializable {
    private Map<String, Link> links;
    // getters, setters
}

public class Link {
    private String href;
    // getters, setters
}

Now instead of extracting the response body as a JSON String, convert it to POJO directly.

public Report getReportListByClientId(String clientId) {
        
        ResponseEntity<Report> responseEntity = null;
        
        try {
            ..
            responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, Report.class);
            
            return responseEntity.getBody();

        } catch (Exception e) {
           ..
        }
}

Assumption: the project has Jackson in classpath, so MappingJacksonHttpMessageConverter will be enabled by default with RestTemplate for the above method to work.

CodePudding user response:

I will try to help u. You can use JsonPath to manipulate your string json.

    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.7.0</version>
    </dependency>

add this library to your code and then try to use this

        String json = """
            {
                "links": {
                    "RCDSO - Production Environment Cost": {
                        "href": "href 1"
                    },
                    "RCDSO - Development & UAT Environment Cost": {
                        "href": "href 2"
                    },
                    "RCDSO - Total Cost for Prod - Compugen Managed": {
                        "href": "href 3"
                    },
                    "RCDSO - Virtual Machine Cost": {
                        "href": "href 4"
                    },
                    "RCDSO - Azure File Storage Cost": {
                        "href": "href 5"
                    },
                    "RCDSO - Azure Backup and Site Recovery": {
                        "href": "href 6"
                    },
                    "RCDSO - Azure App Services Cost": {
                        "href": "href 7"
                    }
                }
            }
            """;
    Map<String, Map<String, String>> links = JsonPath.read(json, "$.links");
    links.forEach((key, value) -> {
        System.out.println("k = "   key);
        System.out.print("v = ");
        value.forEach((key2, value2) -> {
            System.out.println("key = "   key2   " : value = "   value2);
        });
    });
  • Related