在 JSON 数组中获取特定值 (Java)

Getting a specific value inside a JSON array (Java)

我试图获取 JSON 文件中特定属性的值,但我却获取了数组的一行内容。

例如这是我的 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" }
      } 

]
}
}

我只想获取属性的值 "type3" 但是我的以下代码让我得到了所有这些。

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 only want to get this : { "type": "contributor" }

然后像这样(大致)获取该值

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

您可以使用 JsonPath.read 获取所有 Type3 值作为列表。

列表值 = JsonPath.read(bindings, "..type3");