[英]Calling external API and parsing JSON Object
I am trying to fetch JSON from external API and parse it so that I can access JSON object values in order to avoid values(fields) that I do not need. 我正在尝试从外部API提取JSON并对其进行解析,以便可以访问JSON对象值,从而避免了不需要的值(字段)。
I have studied JSONOBject library a little and parsed the objects, however, it feels that I am doing too much hard coding and not doing it correctly at all, feedback is much appreciated. 我稍微研究了JSONOBject库并解析了对象,但是,感觉到我在做过多的硬编码而根本没有正确做,反馈非常感谢。
Output result after user input : 用户输入后的输出结果:
Sending 'GET' request to URL: https://api.coindesk.com/v1/bpi/currentprice/(user input currency) 向网址发送“ GET”请求: https : //api.coindesk.com/v1/bpi/currentprice/(用户输入币种)
Data fetched at UTC time/date : Sep 17, 2019 22:51:00 UTC Description: Ukrainian Hryvnia Rate float: 253737.6633 在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);
}
}
}
I wrote a sample code to demonstrate what I said in comment by using ObjectMapper
to transform response json string into POJO. 我编写了一个示例代码,通过使用
ObjectMapper
将响应json字符串转换为POJO来演示我在评论中所说的内容。
First, create a class, says CoinDeskResponse
to store the transformation result. 首先,创建一个类,如
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
}
Next, create ObjectMapper
and convert the response to CoinDeskResponse
POJO. 接下来,创建
ObjectMapper
并将响应转换为CoinDeskResponse
POJO。 Then you can get desired data by manipulating the object. 然后,您可以通过操作对象来获得所需的数据。
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();
}
Console output: 控制台输出:
Data fetched at UTC time/date : Sep 18, 2013 17:27:00 UTC
在UTC时间/日期获取的数据:UTC 2013年9月18日17:27:00
Description : United States Dollar描述:美元
Rate float : 126.5235浮动利率:126.5235
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.