我正在嘗試構建一個簡單的 Web 應用程式,該應用程式向 x-rapid api 發送請求以檢索有關某個國家/地區的 covid 病例的資訊。
我正在使用 Spring Boot Maven 專案,并且在 RestController 中,我不知道如何從外部 API 獲取回應,將其轉換為 bean,稍后我可以使用它的屬性將它們顯示在 thymeleaf 生成的表中html主頁。
這是回應的正文: {"get":"statistics","parameters":{"country":"romania"},"errors":[],"results":1,"response":[{ “大陸”:“歐洲”,“國家”:“羅馬尼亞”,“人口”:19017233,“病例”:{“新”:“ 4521”,“活躍”:156487,“關鍵”:431,“恢復":2606660,"1M_pop":"148704","total":2827936},"deaths":{"new":" 35","1M_pop":"3407","total":64789},"測驗":{"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 轉換為 RomanData 物件?
uj5u.com熱心網友回復:
為了將您的 JSON 字串轉換為您的 JSON 字串,RomaniaData您可以使用 Jackson 庫,特別是ObjectMapper類及其方法readValue()。如果您的 Json 有一些未知屬性,您可以按照Jackson Unmarshalling JSON with Unknown Properties的描述忽略它們。您也可以使用提供 JsonUtils 類的開源庫 MgntUtils,它無論如何都是 Jackson 庫的包裝器。使用該類決議您的 Json String 將如下所示:
RomaniaData romaniaData = null;
try {
romaniaData = JsonUtils.readObjectFromJsonString(jsonString, RomaniaData.class);
}
} catch (IOException e) {
...
}
可以在此處找到 MgntUtils 庫的 Maven 工件,并且可以在此處的 Github 上找到作為 jar 的庫以及 Javadoc 和源代碼
uj5u.com熱心網友回復:
您可以使用 Jackson Json 序列化器
RomaniaData romaniaData = new ObjectMapper().readValue(responseString, RomaniaData.class);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448552.html
