【发布时间】:2020-02-22 12:31:29
【问题描述】:
我有一个 Java 应用程序,它调用 evepraisal 的 API 来获取商品的特定“价格”: 这是我的代码:
String url = "https://evepraisal.com/appraisal.json";
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "market=jita&raw_textarea=tritanium&persist=no&format=json";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
JSONObject jsonObject = new JSONObject(response);
String sellPrice = jsonObject.getJSONObject("totals").getString("sell");
System.out.println("sell price " + sellPrice);
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
控制台输出:
{
"appraisal":{
"created":1582370316,
"kind":"listing",
"market_name":"jita",
"totals":{
"buy":7.09,
"sell":7.29,
"volume":0.01
},
"items":[
{
"name":"tritanium",
"typeID":34,
"typeName":"Tritanium",
"typeVolume":0.01,
"quantity":1,
"prices":{
"all":{
"avg":7.825135725671236,
"max":6660,
"median":8.49,
"min":0.01,
"percentile":10,
"stddev":12.094503046356275,
"volume":21067715118,
"order_count":83
},
"buy":{
"avg":4.4427463532321685,
"max":7.09,
"median":5,
"min":0.01,
"percentile":7.01,
"stddev":1.243253441213804,
"volume":3668335637,
"order_count":34
},
"sell":{
"avg":8.817038715163093,
"max":6660,
"median":8.49,
"min":7.29,
"percentile":7.32,
"stddev":13.20791605306975,
"volume":17399379481,
"order_count":49
},
"updated":"2020-02-22T11:16:22.644986932Z",
"strategy":"orders"
我想把这个特定的值变成一个 String var : Appraisal --> total --> Sell = 7.29 我认为我的问题来自 getJSONObject 行。我在网上找到了多个教程,但没有一个能正确回答我的需求, 有时我有一个
Exception in thread "main" org.json.JSONException: JSONObject["totals"] not found.
参考
String sellPrice = jsonObject.getJSONObject("totals").getString("sell");
如果有人有滑雪道 我做错了什么? 提前致谢
【问题讨论】:
-
确定要先
.getJSONObject("appraisal")? -
JSONObject["appraisal"] 尝试这样做时找不到
-
您尝试过使用 Gson 吗?它会直接将您的 JSON 转换为对象,然后您可以获得所需的任何值。