如何将外部 REST API 响应正文从 json/字符串转换/使用为 bean - 我正在使用 Spring Boot-Maven
我正在尝试构建一个简单的 Web 应用程序,该应用程序向 x-rapid api 发送请求以检索有关某个国家/地区 covid 病例的信息。
我正在使用 Spring Boot Maven 项目,在 RestController 中,我不知道如何从外部 API 获取响应,将其转换为一个 bean,稍后我可以使用它的属性将它们显示在 thymeleaf 生成的表中html 主页。
这是响应的正文: {"get":"统计","参数":{"国家":"罗马尼亚"},"错误":[],"结果":1,"响应":[{"大陆": "欧洲","国家":"罗马尼亚","人口":19017233,"病例":{"新":"+4521","活跃":156487,"严重":431, “恢复”:2606660,“1M_pop”:“148704”,“总计”:2827936},“死亡”:{“新”:“+35”,“1M_pop”:“3407”,“总计”:6478 9},"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 对象?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 Jackson Json 序列化器
You can use Jackson Json Serializer
为了将 JSON 字符串转换为
RomaniaData
,您可以使用 Jackson 库,特别是 ObjectMapper 类及其方法 readValue()。如果你的 Json 有一些未知的属性,你可以按照描述忽略它们 Jackson Unmarshalling JSON with Unknown属性。您还可以使用提供类 JsonUtils 的开源库 MgntUtils 无论如何,它是 Jackson 库的包装。使用该类解析 Json 字符串将如下所示:
可以找到 MgntUtils 库的 Maven 工件 这里,并且可以在 Github 上找到作为 jar 的库以及 Javadoc 和源代码 此处
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:
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