Spring Boot GET请求到API [英] Spring Boot GET request to API

查看:194
本文介绍了Spring Boot GET请求到API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有这个 JSON数据以原始格式.它只是简单地表示世界各地当前的covid-19记录.我需要向其发送一个GET请求,并使用Spring Boot在浏览器中显示数据.我已经尝试过getForObject(url, class)方法,但是它给出了错误消息no suitable HttpMessageConverter found for response type.我已经尝试解决它,但是无法解决.然后,我尝试使用ObjectMapper.readValue(url, class)方法和JSON数据的URL和Covid19.class.这次,我收到一条错误消息no protocol.以下是项目的结构:

So, I have this JSON data which is in raw format. It simply denotes the current covid-19 records around the world day by day. I need to send a GET request to it and display the data in the browser by using Spring Boot. I have tried getForObject(url, class) method, but it gave an error with a message no suitable HttpMessageConverter found for response type. I have tried to solve it but could not. Then I have tried the ObjectMapper.readValue(url, class) method with the URL of JSON data and Covid19.class. This time, I get an error with a message no protocol. Following is the structure of the project:

Covid19.java:

public class Covid19 implements Serializable {
    private final String country;

    public Covid19(String country){
        this.country = country;
    }

    public String getCountry(){
        return country;
    }
}

Covid19Controller.java:

@RestController
public class Covid19Controller {
    @GetMapping(value = "/covid", produces = MediaType.APPLICATION_JSON_VALUE)
    public Covid19 covid19() throws IOException {
        URL url = new URL("raw.githubusercontent.com/pomber/covid19/master/docs/timeseries.json");
        Covid19 covid19 = new ObjectMapper().readValue(url, Covid19.class);
        return covid19;
    }

主类:

public static void main(String[] args) {
    SpringApplication.run(DataminingWebserviceApplication.class, args);
}

实际上,我的目标是发送带有参数country的GET请求,但一开始就停滞不前.我昨天开始学习Spring Boot并尝试学习它.有很多教程,但没有一个适合我的情况.预先感谢.

Actually my aim was to send a GET Request with parameter country but stuck at the very beginning. I have started to study Spring Boot yesterday and trying to learn it. There are plenty of tutorials but none fits my case so well. Thanks in advance.

推荐答案

您定义的类不正确,请创建这样的类

The class you have defined is not correct, Create a class like this

@JsonIgnoreProperties(ignoreUnknown = true)
public class Covid19{
    private int confirmed;
    private int deaths;
     ....
    // add other fields and Getters & Setters
}

读取数据的代码应如下所示

And the code to read the data should look like this

URL url = new URL("https://raw.githubusercontent.com/pomber/covid19/master/docs/timeseries.json");
final Map<String, List<Covid19>> covid19Map= new ObjectMapper().readValue(url, new TypeReference<Map<String, List<Covid19>>>() {});

covid19Map将把密钥作为国家/地区,并将值作为日期明智的列表,如json中所示

covid19Map will have the key as country and the valus as date wise list as indicated in the json

这篇关于Spring Boot GET请求到API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆