Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Parse (JSON Object Not Found) Java

Tags:

java

json

arrays

I have a JSON file format in a variable called "json" that I want to parse. However, I'm getting this error message:

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

This is the code I'm using:

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);
}

This is the JSON I'm trying to parse:

{
  "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" }
      } 

]
}
}

Even when I execute the following without the for loop it keeps showing the same error msg.

JSONObject obj =  new JSONObject(json);            
JSONArray bindings = obj.getJSONArray("bindings");  
like image 952
ichmode Avatar asked Jun 23 '26 07:06

ichmode


1 Answers

You need to pass by the results JSONObject first in order to get to your JSONArray:

JSONObject obj =  new JSONObject(json);           
JSONObject results = obj.getJSONObject("results"); 
JSONArray bindings = results.getJSONArray("bindings");     
like image 146
Mohammed Aouf Zouag Avatar answered Jun 24 '26 20:06

Mohammed Aouf Zouag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!