问题描述
请帮我理解为什么这个java程序没有从json文件中找到数组。我没有通过谷歌找到类似类型的 json 文件,所以请教我。
错误:
C:\temp\example.json
org.json.JSONException: JSONObject["result"] not found.
at org.json.JSONObject.get(JSONObject.java:572)
at org.json.JSONObject.getJSONArray(JSONObject.java:765)
at JsonParsingMachine.main(JsonParsingMachine.java:17)
.java 内容:
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.json.*;
public class JsonParsingMachine {
public static void main(String[] args) {
String tiedosto = "C:/temp/example.json";
System.out.println(Paths.get(tiedosto));
try {
String contents = new String((Files.readAllBytes(Paths.get(tiedosto))));
JSONObject o = new JSONObject(contents);
JSONArray res = o.getJSONArray("result");
for (int i = 0; i < res.length(); i++) {
System.out.println();
}
} catch (Exception e) {
e.printstacktrace();
}
}
}
json 文件(example.json)
{
"quoteResponse" : {
"result" : [ {
"language" : "en-US","region" : "US","quoteType" : "EQUITY","quoteSourceName" : "Nasdaq Real Time Price","triggerable" : true
} ]
}
}
解决方法
result
数组在 quoteResponse
JSONObject 内。你需要这样做:
JSONObject o = new JSONObject(contents);
JSONObject quoteResponse = o.getJSONObject("quoteResponse");
JSONArray res = quoteResponse.getJSONArray("result");