JSON解析(未找到JSON对象)Java

3

我有一个变量名为"json"的JSON文件格式需要解析。但是,我遇到了以下错误信息:

Exception in thread "main" org.json.JSONException: JSONObject["bindings"] not found.

这是我正在使用的代码:

JSONObject obj =  new JSONObject(json);            
JSONArray bindings = obj.getJSONArray("bindings");       

for (int i=0; i<obj.length(); i++)
{
JSONObject x = bindings.getJSONObject(i);                
x.getJSONObject("type1").getString("type");  
System.out.println(x);
}

这是我正在尝试解析的JSON:

{
  "head": {
    "vars": [ "type1" , "pred" , "type2" ]
  } ,
  "results": {
    "bindings": [
      {
        "type1": { "type": "Collection" } ,
        "type2": { "type": "has" } ,
        "type3": { "type": "contributor" }
      } ,
      {
        "type1": { "type": "Collection2" } ,
        "type2": { "type": "has2" } ,
        "type3": { "type": "contributor2" }
      } 

]
}
}

即使我不使用for循环执行以下操作,它仍然显示相同的错误消息。
JSONObject obj =  new JSONObject(json);            
JSONArray bindings = obj.getJSONArray("bindings");  
1个回答

4

要访问你的JSONArray,你需要首先通过结果中的JSONObject

JSONObject obj =  new JSONObject(json);           
JSONObject results = obj.getJSONObject("results"); 
JSONArray bindings = results.getJSONArray("bindings");     

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接