ichmode
ichmode

Reputation: 67

Getting a specific value inside a JSON array (Java)

I'm trying to get the value of a specific attribute in a JSON file but instead I get a row content of the array.

For example that's my JSON file:

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

]
}
}

I want to get only the values of attribute "type3" But my following code gets me all of them.

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

for (int i=0; i<bindings.length(); i++)
{
JSONObject x = bindings.getJSONObject(i);                
x.getJSONObject("type3");  
}

I tried several approaches but it seems I'm doing it wrong.

Upvotes: 1

Views: 3107

Answers (2)

Sarabala
Sarabala

Reputation: 424

you can use JsonPath.read to get all Type3 values as list.

List value = JsonPath.read(bindings, "..type3");

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 191743

I only want to get this : { "type": "contributor" }

Then get that value (roughly) like so

bindings.getJSONObject(0).getJSONObject("type3")

Upvotes: 2

Related Questions