我刚刚开始搞乱一些网络编程,并试图从音乐网站的 API 中检索有关某些音乐艺术家的信息。我正在使用此处找到的 JSON.simple 工具包。
这是我的代码。两个类,一个是JSONReader
:
import org.json.simple.*;
import org.json.simple.parser.*;
import java.net.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
public class JSONReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, ParseException {
JSONParser parser = new JSONParser();
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
Object obj = parser.parse(jsonText);
JSONObject result = (JSONObject) obj;
return result;
} finally {
is.close();
}
}
}
好的,这是我的Main
课:
public class Main {
public static void main(String[] args) throws Exception {
System.out.println("Starting execution of program...");
String searchQuery = args[0];
JSONReader reader = new JSONReader();
System.out.println("Beginning HTTP request...");
String baseURL = "http://api.discogs.com/database/search?q=" + searchQuery + "&type=artist";
JSONObject json = reader.readJsonFromUrl(baseURL);
System.out.println(json);
末尾的打印语句main
给了我这个:
{"results":[{"id":22898,"title":"Tool","type":"artist","resource_url":"http:\/\/api.discogs.com\/artists\/22898","uri":"\/artist\/Tool","thumb":null},{"id":5481,"title":"DJ Tool","type":"artist","resource_url":"http:\/\/api.discogs.com\/artists\/5481","uri":"\/artist\/DJ+Tool","thumb":null},{"id":186087,"title":"Tool (3)","type":"artist","resource_url":"http:\/\/api.discogs.com\/artists\/186087","uri":"\/artist\/Tool+%283%29","thumb":null},{"id":108078,"title":"Rave Tool","type":"artist","resource_url":"http:\/\/api.discogs.com\/artists\
还有大约十几位艺术家,他们都以花括号和逗号分隔。
所以我results
通过这样做“得到”:
System.out.println(json.get("results"));
最后得到:
[{"id":22898,"title":"Tool","type":"artist","resource_url":"http:\/\/api.discogs.com\/artists\/22898","uri":"\/artist\/Tool","thumb":null},{"id":5481,"title":"DJ Tool", ... ]
问题是,我希望能够从搜索结果中提取所有十几位艺术家。
我将上面的内容转换JSONArray
为如下所示,然后我可以“获取”搜索结果的索引。在这篇长文之后,我的问题是:为什么会这样?本质上JSONObject
,如果它需要成为JSONArray
访问结果的索引才能工作,那么首先的意义是什么?另外,是否有原因我不能将解析结果jsonText
直接设置为 a JSONArray
?readJsonFromUrl
当我尝试将方法中的所有“JSONObject”更改为JSONArrays
时,会发生错误,说它无法将 aJSONObject
转换为JSONArray
. 为什么是这样?
JSONArray json1 = (JSONArray) reader.readJsonFromUrl(baseURL).get("results");
System.out.println(json1);
System.out.println(json1.get(0));