![](/img/trans.png)
[英]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.