繁体   English   中英

如何将外部 REST API 响应主体从 json/string 转换/使用到 bean - 我正在使用 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 发送请求以检索有关某个国家/地区的 covid 病例的信息。

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

这是响应的主体:{"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;
    }

如何将 responseString 转换为 RomaniaData object?

您可以使用 Jackson Json 序列化器

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

为了将 JSON 字符串转换为RomaniaData ,您可以使用 Jackson 库,特别是ObjectMapper class 及其方法readValue() 如果您的 Json 有一些未知属性,您可以忽略它们,如Jackson Unmarshalling JSON with Unknown Properties所述。 您也可以使用提供 class JsonUtils的开源库 MgntUtils,它是 Jackson 库的包装器。 使用 class 解析您的 Json 字符串将如下所示:

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

可以在此处找到 MgntUtils 库的 Maven 工件,可以在此处的 Github 上找到作为 jar 的库以及 Javadoc 和源代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM