在JSON数组中获取特定值(Java)
我试图获取JSON文件中特定属性的值,但得到的是数组的行内容 例如,这是我的JSON文件:在JSON数组中获取特定值(Java),java,arrays,json,jsonobject,Java,Arrays,Json,Jsonobject,我试图获取JSON文件中特定属性的值,但得到的是数组的行内容 例如,这是我的JSON文件: { "head": { "vars": [ "type1" , "pred" , "type2" ] } , "results": { "bindings": [ { "type1": { "type": "Collection" } , "type2": { "type": "has" } , "type3": {
{
"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");
}
JSONObject obj=新的JSONObject(json);
JSONObject results=obj.getJSONObject(“结果”);
JSONArray bindings=results.getJSONArray(“bindings”);
对于(int i=0;i
我只想得到这个:{“type”:“contributor”}
然后像这样(粗略地)得到那个值
我只想得到这个:{“type”:“contributor”}
然后像这样(粗略地)得到那个值
您可以使用JsonPath.read将所有Type3值作为列表获取
List value=JsonPath.read(绑定,“…type3”);您可以使用JsonPath.read将所有type3值作为List获取
List value=JsonPath.read(bindings,“…type3”);为什么要在json上迭代,这是一个单一的对象,而不是在result下迭代绑定,例如..for(int i=0;iI尝试了(int i=0;iI认为这里,您得到的是类型3的值为“{”type:“contributor2”}”。没错。你还想得到什么?我实际上得到了这个:“类型1”:{“类型”:“集合”},“类型2”:{“类型”:“has”},“类型3”:{“类型”:“contributor”}。我只想得到这个:{“类型”:“contributor”}。你想要什么具体值?你的代码清楚地表明你明白什么时候使用数组和对象。从一个对象,你可以对一个键执行一个简单的get
。为什么你要迭代json,这是一个单一的对象,你不应该在result下迭代绑定,例如..for(int i=0;iI)尝试使用(inti=0;我想在这里,你得到的是type3的值为“{”type:“contributor2”}”。这是正确的。你还想得到什么?我实际上得到的是:“type1:{”type:“Collection”},“type2:{”type:“has”},“type3:{”type:“contributor”}。我只想得到这个:{”type:“contributor”}。您想要什么特定值?您的代码清楚地表明您了解何时使用数组和对象。从对象,您可以对键执行简单的get
bindings.getJSONObject(0).getJSONObject("type3")