Java 调用外部API并解析JSON对象

Java 调用外部API并解析JSON对象,java,json,api,Java,Json,Api,我正在尝试从外部API获取JSON并对其进行解析,以便能够访问JSON对象值,从而避免不需要的值字段 我对JSONOBject库进行了一些研究,并对对象进行了解析,但是,我觉得我做了太多的硬编码,根本没有正确地进行编码,所以非常感谢反馈 用户输入后的输出结果: 正在向URL发送“获取”请求:输入货币 在UTC时间/日期获取的数据:2019年9月17日22:51:00 UTC 描述:乌克兰格里夫尼亚 浮动利率:253737.6633 import org.json.JSONObject; impo

我正在尝试从外部API获取JSON并对其进行解析,以便能够访问JSON对象值,从而避免不需要的值字段

我对JSONOBject库进行了一些研究,并对对象进行了解析,但是,我觉得我做了太多的硬编码,根本没有正确地进行编码,所以非常感谢反馈

用户输入后的输出结果:

正在向URL发送“获取”请求:输入货币

在UTC时间/日期获取的数据:2019年9月17日22:51:00 UTC 描述:乌克兰格里夫尼亚 浮动利率:253737.6633

import 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("---------------------------------------------");

            //creating reader instance to reade the response from the HTTP GET request
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String userInputLine;
            StringBuilder response = new StringBuilder();

            //if there is still something to read from -> then read and append to String builder -> can be mutable
            while ((userInputLine = reader.readLine()) != null) {
                response.append(userInputLine);
            }

            //closing reader
            reader.close();

            //Converting response to JSON object
            JSONObject myresponse = new JSONObject(response.toString());


            JSONObject bpiObject = new JSONObject(myresponse.getJSONObject("bpi").toString());
            JSONObject currencyObjects = new JSONObject(bpiObject.getJSONObject(userInput).toString());

            // since response got a objects within objects, we need to dig dipper in order to access field values
            JSONObject timeObject = new JSONObject(myresponse.getJSONObject("time").toString());
            System.out.println("Data fetched at UTC time/date : " + timeObject.getString("updated"));

            System.out.println("Description : " + currencyObjects.getString("description") + "\nRate float : " + currencyObjects.getString("rate_float"));


        } catch (Exception e) {
            System.out.println(e);

        }

    }
}

我编写了一个示例代码,通过使用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并将响应转换为CointDeskResponse POJO。然后,您可以通过操纵对象来获得所需的数据

    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


您可以使用ObjectMapper将json字符串转换为Java对象进行操作。@LHCHIN嘿,谢谢,我知道我可以用FieldsObject创建一个POJO类,但在->之后如何将dipper挖掘到这些json对象中,例如,如果有json对象{time}时间有一个名为under updated的字段,我如何访问该字段。当然,字符串responsest可以替换为我的API端点,对吗@LHCHIN@Tim普罗佐罗夫:当然,您可以将其替换为response.toString。我已添加了所有POJO类,并将上面的字符串更改为response.toString>我已收到时间对象,但其他两个对象是null@TimProzorov你有没有检查response.toString的结果?它是否包含那些json对象,例如免责声明或bpi?我必须为bpi对象创建另一个包装器类,因为默认情况下USD始终存在,所以它提供了两个对象映射bpi;