为了账号安全,请及时绑定邮箱和手机立即绑定

调用外部API并解析JSON对象

调用外部API并解析JSON对象

慕妹3146593 2023-08-04 15:49:45
我正在尝试从外部 API 获取 JSON 并解析它,以便我可以访问 JSON 对象值,以避免我不需要的值(字段)。我已经研究了一点 JSONOBject 库并解析了对象,但是,感觉我做了太多的硬编码并且根本没有正确执行,非常感谢反馈。用户输入后输出结果:发送“GET”请求到 URL: https: //api.coindesk.com/v1/bpi/currentprice/(用户输入货币)数据在 UTC 时间/日期获取:2019 年 9 月 17 日 22:51:00 UTC 说明:乌克兰格里夫纳汇率浮动:253737.6633import org.json.JSONObject;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;public class App {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        System.out.println("Please enter the currency you would like to get BTC current rate for");        String userInput = in.readLine();        try {            String url = "https://api.coindesk.com/v1/bpi/currentprice/" + userInput;            URL obj = new URL(url);            // HttpURLConnection instance is making a request            //openConnection() method of URL class opens the connection to specified URL            HttpURLConnection con = (HttpURLConnection) obj.openConnection();            // saving the response code from the request            int responseCode = con.getResponseCode();            System.out.println("\nSending 'GET' request to URL : " + url);            System.out.println("---------------------------------------------");            System.out.println("Response Code from the HTTP request : " + responseCode);            System.out.println("---------------------------------------------");            }
查看完整描述

1 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

ObjectMapper我编写了一个示例代码,通过使用将响应 json 字符串转换为 POJO 来 演示我在评论中所说的内容。


首先,创建一个类,说CoinDeskResponse是存储转换结果。


public class CoinDeskResponse {

    private TimeInfo time;

    private String disclaimer;

    private BpiInfo bpi;

    //general getters and setters

}


class TimeInfo {

    private String updated;

    private String updatedISO;

    //general getters and setters

}


class BpiInfo {

    private String code;

    private String symbol;

    private String rate;

    private String description;


    @JsonProperty("rate_float")

    private String rateFloat;

    //general getters and setters

}

接下来,创建ObjectMapper响应并将其转换为CoinDeskResponsePOJO。然后就可以通过操作该对象来获取所需的数据。


    String responseStr = "{\"time\":{\"updated\":\"Sep 18, 2013 17:27:00 UTC\",\"updatedISO\":\"2013-09-18T17:27:00+00:00\"},\"disclaimer\":\"This data was produced from the CoinDesk Bitcoin Price Index. Non-USD currency data converted using hourly conversion rate from openexchangerates.org\",\"bpi\":{\"code\":\"USD\",\"symbol\":\"$\",\"rate\":\"126.5235\",\"description\":\"United States Dollar\",\"rate_float\":126.5235}}";

    ObjectMapper mapper = new ObjectMapper();

    try {

        CoinDeskResponse coinDeskResponse = mapper.readValue(responseStr, CoinDeskResponse.class);


        System.out.println(coinDeskResponse.getTime().getUpdated());

        System.out.println(coinDeskResponse.getBpi().getDescription());

        System.out.println(coinDeskResponse.getBpi().getRateFloat());

    } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }

控制台输出:


数据在 UTC 时间/日期获取:2013 年 9 月 18 日 17:27:00 UTC

描述:美元

浮动汇率:126.5235


查看完整回答
反对 回复 2023-08-04
  • 1 回答
  • 0 关注
  • 130 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信