我试图使用org/ JSON /json/20171018存储库(http://central.maven.org/maven2/org/json/json/20171018/ -> json-20171018.jar)在我的java应用程序中读取一个json文件。我的JSON文件如下所示:
{
"manifest_version": 2,
"name": "Chrome Extension",
"version": "0.1",
"permissions": [
"tabs"
],
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"background": {
"matches": [
"google.de",
"youtube.com",
"wikipedia.de"
],
"scripts": ["background.js"],
"persistent": true
}
}我对background一节感兴趣,更具体的是background matches到的链接。因此,我首先创建了整个文件的JSONObject,然后创建了background部分的JSONObject,然后创建了类型为matches的JSONArray。但不幸的是,我在运行程序时出现了这个错误:
Exception in thread "main" org.json.JSONException: JSONObject["matches"] not found.
at org.json.JSONObject.get(JSONObject.java:520)
at org.json.JSONObject.getJSONArray(JSONObject.java:714)
at Json.main(Json.java:19)我的java代码如下所示:
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Json {
public static void main(String[] args){
String loc = new String("chromeAdon/manifest.json");
File file = new File(loc);
try {
String content = new String(Files.readAllBytes(Paths.get(file.toURI())));
JSONObject json = new JSONObject(content);
JSONObject json2 = new JSONObject(json.getJSONObject("background"));
JSONArray jarray = json2.getJSONArray("matches");
for (int i=0;i<jarray.length();i++){
System.out.println(jarray.getString(0));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}有人知道我的错误在哪里吗?
发布于 2019-10-30 20:54:55
您正在包装getJSONObject("background")返回的JSON对象,这是不需要的。
只需使用返回的对象:
JSONObject jsonContent = new JSONObject(content);
JSONObject jsonBackground = jsonContent.getJSONObject("background");
JSONArray jsonArrayMatches = jsonBackground.getJSONArray("matches");https://stackoverflow.com/questions/58633466
复制相似问题