[英]How to get the first object in an JSONObject without knowing the name?
[英]JSONObject get value of first node regardless of name
我想知道是否有办法在不知道其名称的情况下获取JSONObject的第一个子节点的值:
我有一些JSON进来了一个叫做this_guy
的节点
{"this_guy": {"some_name_i_wont_know":"the value i care about"}}
使用JSONObject,如果我不知道孩子的名字,怎么能干净利落地得到“我关心的价值”。 我所知道的只是“this_guy”,有人吗?
使用JSONObject.keys() 返回此对象中String名称的迭代器 。 然后使用这些键来检索值。
仅获得第一个值:
Iterator<String> keys = jsonObject.keys();
// get some_name_i_wont_know in str_Name
String str_Name=keys.next();
// get the value i care about
String value = json.optString(str_Name);
Object obj = parser.parse(new FileReader("path2JsonFIle"));
JSONObject jsonObject = (JSONObject) obj;
试试这个迭代器
JSONObject jsonObj = (JSONObject)jsonObject.get("this_guy");
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
/*check here for the appropriate value and do whatever you want*/
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
}
一旦你得到了适当的值,就摆脱循环。 例如,你说你需要的只是内部地图中的第一个值。 所以试试像
int count = 0;
String valuINeed="";
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
valueINeed = (String)keyvalue;
count++;
/*check here for the appropriate value and do whatever you want*/
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
if(count==1)
break;
}
System.out.println(valueINeed);
如果您只关心价值而不关心关键,您可以直接使用:
Object myValue = fromJson.toMap().values().iterator().next();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.