我试图使用org.json库在线使用一个json文件,但是当我用gradle运行它时,它会给我错误:
at org.json.JSONTokener.syntaxError(JSONTokener.java:507)
at org.json.JSONObject.<init>(JSONObject.java:222)
at org.json.JSONObject.<init>(JSONObject.java:406)
at me.h0rb.bot.Main.readJsonFromUrl(Main.java:42)
at me.h0rb.bot.Main.main(Main.java:50)
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':Main.main()'.
> Process 'command '/usr/lib/jvm/java-11-openjdk-amd64/bin/java'' finished with non-zero exit value 1
我想不出问题所在,代码如下:
package me.h0rb.bot;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
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, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("https://2b2t.io/api/queue");
System.out.println(json.toString());
System.out.println(json.get("id"));
}
}
1条答案
按热度按时间brvekthn1#
如果我打开url,我会看到一个json数组(数组以
[
)而不是对象(以{
).您实际上有一个数组,而不是一个json对象。所以我会用
JSONArray
而不是JSONObject
在你的代码里。