我有一个网站,我必须用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"]不是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();
}
}
答案 0 :(得分:2)
dataset
的{{1}}字段是JSONObject而不是JSONArray。改变这个:
jsonobjects
到此:
jsonobjects.getJSONArray("dataset");