skip to Main Content

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 CustomOlapReports getReportListByClientId(String clientId) {
        ResponseEntity<CustomOlapReports> responseEntity = null;
        CustomOlapReports 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, CustomOlapReports.class);
            
            jsonResponse =  responseEntity.getBody();   
        } catch (Exception e) {
            e.printStackTrace();
        }
    return jsonResponse;
}

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

{
    "responseMessage": "SUCCESS",
    "status": "OK",
    "statusCode": 1,
    "response": {
        "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"
            }
        }
    }
}

/********************** CustomOlapReports.java *************************/

@Getter
@Setter
public class CustomOlapReports {
    
     @JsonProperty("links") 
     private Links links;
}
/********************** Links.java *************************/
@Setter
@Getter
public class Links {
    @JsonProperty("RCDSO - Production Environment Cost")
    private RCDSOProductionEnvironmentCost rCDSOProductionEnvironmentCost;
    
    @JsonProperty("RCDSO - Development & UAT Environment Cost")
    private RCDSODevelopmentUATEnvironmentCost rCDSODevelopmentUATEnvironmentCost;
    
    @JsonProperty("RCDSO - Total Cost for Prod - Compugen Managed")
    private RCDSOTotalCostForProdCompugenManaged rCDSOTotalCostForProdCompugenManaged;
    
    @JsonProperty("RCDSO - Virtual Machine Cost")
    private RCDSOVirtualMachineCost rCDSOVirtualMachineCost;
    
    @JsonProperty("RCDSO - Azure File Storage Cost")
    private RCDSOAzureFileStorageCost rCDSOAzureFileStorageCost;
    
    @JsonProperty("RCDSO - Azure Backup and Site Recovery")
    private RCDSOAzureBackupAndSiteRecovery rCDSOAzureBackupAndSiteRecovery;
    
    @JsonProperty("RCDSO - Azure App Services Cost")
    private RCDSOAzureAppServicesCost rCDSOAzureAppServicesCost;
}
/********************** RCDSOProductionEnvironmentCost.java *************************/
@Getter
@Setter
public class RCDSOProductionEnvironmentCost {
    @JsonProperty("href")
    private String href;
}
/********************** RCDSODevelopmentUATEnvironmentCost.java *************************/
@Getter
@Setter
public class RCDSODevelopmentUATEnvironmentCost {
    @JsonProperty("href")
    private String href;
}
/********************** RCDSOTotalCostForProdCompugenManaged.java *************************/
@Getter
@Setter
public class RCDSOTotalCostForProdCompugenManaged {
    @JsonProperty("href")
    private String href;
}
/********************** RCDSOVirtualMachineCost.java *************************/
@Getter
@Setter
public class RCDSOVirtualMachineCost {
    @JsonProperty("href")
    private String href;
}
/********************** RCDSOAzureFileStorageCost.java *************************/
@Getter
@Setter
public class RCDSOAzureFileStorageCost {
    @JsonProperty("href")
    private String href;

}
/********************** RCDSOAzureBackupAndSiteRecovery.java *************************/
@Getter
@Setter
public class RCDSOAzureBackupAndSiteRecovery {
    @JsonProperty("href")
    private String href;

}
/********************** RCDSOAzureAppServicesCost.java *************************/
@Getter
@Setter
public class RCDSOAzureAppServicesCost {
    @JsonProperty("href")
    private String href;

}

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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);
            });
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search