JSONObject 获取第一个节点的值而不考虑名称

JSONObject get value of first node regardless of name

我想知道是否有办法在不知道其名称的情况下获取 JSONObject 的第一个 child 的值:

我有一些 JSON 进来了一个名为 this_guy

的节点
{"this_guy": {"some_name_i_wont_know":"the value i care about"}}

使用JSONObject,如果我不知道child的名字,我怎么能干净地得到"the value i care about,"呢?我只知道 "this_guy",有人吗?

使用 JSONObject.keys(),其中 returns 此对象中字符串名称的迭代器 。然后使用这些键检索值。

只获取第一个值:

 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();