Home > OS >  How do I convert/consume an external REST API response body from json/string to bean - I'm usin
How do I convert/consume an external REST API response body from json/string to bean - I'm usin

Time:03-24

I'm trying to build a simple web app which sends a request to x-rapid api to retrieve information about covid cases in a country.

I am using Spring Boot Maven project and, in the RestController, I don't know how to take the response from the external API, turn it into a bean which I can later use its properties to have them displayed in a thymeleaf generated table on the html homepage.

This is the body of the response: {"get":"statistics","parameters":{"country":"romania"},"errors":[],"results":1,"response":[{"continent":"Europe","country":"Romania","population":19017233,"cases":{"new":" 4521","active":156487,"critical":431,"recovered":2606660,"1M_pop":"148704","total":2827936},"deaths":{"new":" 35","1M_pop":"3407","total":64789},"tests":{"1M_pop":"1149360","total":21857638},"day":"2022-03-23","time":"2022-03-23T16:15:03 00:00"}]}

@RestController
public class CovidTrackerRestController {
    
    @Autowired
    private RestTemplate restTemplate;
    
//RomaniaData class has been created to take in the relevant json properties and ignore the rest
//I want to use spring boot to call the setters of this class and populate them with the relevant
//json properties
//I'm thinking of later persisting this data to a mysql database
    @Autowired
    private RomaniaData romaniaData;

    @GetMapping("/hello")
    public String showCovidInformation() {
        
        // connect to a covid database
                        
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://covid-193.p.rapidapi.com/statistics?country=romania"))
                .header("X-RapidAPI-Host", "covid-193.p.rapidapi.com")
                .header("X-RapidAPI-Key", "mykey")
                .method("GET", HttpRequest.BodyPublishers.noBody())
                .build();
        HttpResponse<String> response = null;
        
        try {
            response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //System.out.println(response.body());
        
        //I need to transform the response from the X-RapidAPI from Json to Java Object to send it to my thymeleaf html page 
        // to be displayed in a table.
        
        // get the information
        String responseString = response.body();
        
        // format the information
        System.out.println(response.body());
                
        
        // send the information to html page
        return "/tracker";
    }
    
    private HttpHeaders getHeaders() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.add("covid-193.p.rapidapi.com", "mykey");
        return httpHeaders;
    }

How do I transform the responseString into a RomaniaData object?

CodePudding user response:

You can use Jackson Json Serializer

RomaniaData romaniaData = new ObjectMapper().readValue(responseString, RomaniaData.class);

CodePudding user response:

In order to convert your JSON string into your RomaniaData you can use Jackson library, and in particular ObjectMapper class and its method readValue(). If your Json has some unknown properties you can ignore them as described Jackson Unmarshalling JSON with Unknown Properties. Also you can use an Open-source library MgntUtils that provides class JsonUtils which is a wrapper over Jackson library anyway. With that class parsing your Json String would look like this:

RomaniaData romaniaData = null;
try {
      romaniaData = JsonUtils.readObjectFromJsonString(jsonString, RomaniaData.class);
    }
} catch (IOException e) {
   ...
}

The Maven artifacts for MgntUtils library could be found here, and library as a jar along with Javadoc and source code could be found on Github here

  • Related