java 无论名称如何,JSONObject 都会获取第一个节点的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33531041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSONObject get value of first node regardless of name
提问by erik
I am wondering if there is a way to get the value of the first child of a JSONObject without knowing its name:
我想知道是否有办法在不知道其名称的情况下获取 JSONObject 的第一个孩子的值:
I have some JSON coming in with a node called, this_guy
我有一些 JSON 和一个名为的节点, this_guy
{"this_guy": {"some_name_i_wont_know":"the value i care about"}}
Using JSONObject, how can I get "the value i care about," cleanly if I don't know the name of the child. All I know is "this_guy", anyone?
使用 JSONObject,如果我不知道孩子的名字,我怎样才能干净利落地获得“我关心的价值”。我只知道“this_guy”,有人吗?
回答by ρяσ?ρ?я K
Use JSONObject.keys()which returns an iterator of the String names in this object. then use these keys to retrieve values.
使用JSONObject.keys() ,其返回字符串名称的迭代此对象。然后使用这些键来检索值。
To get only first value:
只获取第一个值:
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);
回答by AbtPst
Object obj = parser.parse(new FileReader("path2JsonFIle"));
JSONObject jsonObject = (JSONObject) obj;
try this iterator
试试这个迭代器
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);
}
once you get the appropriate value, just break out of the loop. for example you said that all you need is the first value in the inner map. so try womething like
一旦获得适当的值,就跳出循环。例如,您说您需要的只是内部地图中的第一个值。所以试试看
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);
回答by xMichal
if you care only about the value and not about the key, you can use directly this:
如果您只关心值而不关心键,则可以直接使用:
Object myValue = fromJson.toMap().values().iterator().next();