简体   繁体   中英

JSONObject get value of first node regardless of name

I am wondering if there is a way to get the value of the first child of a JSONObject without knowing its name:

I have some JSON coming in with a node called, 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?

Use JSONObject.keys() which returns an iterator of the String names in this object . then use these keys to retrieve values.

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

如果您只关心价值而不关心关键,您可以直接使用:

Object myValue = fromJson.toMap().values().iterator().next();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM