我如何 convert/consume 从 json/string 到 bean 的外部 REST API 响应主体 - 我正在使用 Spring Boot-Maven

How do I convert/consume an external REST API response body from json/string to bean - I'm using Spring Boot-Maven

我正在尝试构建一个简单的 Web 应用程序,它向 x-rapid api 发送请求以检索有关某个国家/地区新冠肺炎病例的信息。

我正在使用 Spring Boot Maven 项目,并且在 RestController 中,我不知道如何从外部获取响应 API,将其转换为我稍后可以使用的 bean使用其属性将它们显示在 html 主页上生成的 table thymeleaf 中。

这是回复的正文: {"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","总计":21857638},"天":"2022-03-23","时间":"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;
    }

如何将 responseString 转换为 RomaniaData 对象?

你可以使用 Jackson Json 序列化器

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

为了将您的 JSON 字符串转换为您的 RomaniaData,您可以使用 Jackson 库,尤其是 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。 您也可以使用 Open-source 库 MgntUtils,它提供 class JsonUtils 无论如何它是 Jackson 库的包装器。使用 class 解析你的 Json 字符串将如下所示:

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

可以找到 MgntUtils 库的 Maven 工件 here, and library as a jar along with Javadoc and source code could be found on Github here