gpt4 book ai didi

java - 将 JSONObject 转换为 JSONArray 异常

转载 作者:行者123 更新时间:2023-12-02 02:44:52 28 4
gpt4 key购买 nike

我有一个网站,我必须用 Java 进行查询。在这里您可以看到数据集

https://www.quandl.com/api/v3/datasets/SSE/HYQ.json?start_date=2017-01-01&end_date=2017-01-31

一开始,我以为这是一个 JSONArray,但 Eclipse 总是告诉我,它不是。

因此我尝试从 JSONObject 转换为 JSONArray 但收到此错误:

org.json.JSONException: JSONObject["dataset"] is not a JSONArray.

我做错了什么?

这是我的代码:

package query;

import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

import java.util.*;
import java.io.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Stockquery {

public static void main(String[] args) {

String jsonString = callURL(
"https://www.quandl.com/api/v3/datasets/SSE/HYQ.json?start_date=2017-01-01&end_date=2017-01-31");
// System.out.println("\n\njsonString: " + jsonString);

try {
JSONObject jsonobjects = new JSONObject(jsonString);
System.out.println("\n\njsonArray: " + jsonobjects);
JSONArray arr = jsonobjects.getJSONArray("dataset");

for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
System.out.println(obj);
}

} catch (JSONException e) {
e.printStackTrace();
}

}

public static String callURL(String myURL) {
// System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}

return sb.toString();
}

}

最佳答案

dataset jsonobjects领域是 JSONObject 而不是 JSONArray。更改此:

jsonobjects.getJSONArray("dataset");

对此:

JSONObject dataset = jsonobjects.getJSONObject("dataset");
JSONArray array = dataset.getJSONArray("data");

关于java - 将 JSONObject 转换为 JSONArray 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44765831/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com