JSONObject gets the value of the 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 JSON included in a node call, this_guy

 {"this_guy": {"some_name_i_wont_know":"the value i care about"}} 

Using JSONObject, how can I get a โ€œvalue that I care aboutโ€ if I don't know the name of the child. All I know is "this_guy", anyone?

+5
source share
2 answers

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

To get only the 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); 
+9
source
 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); } 

as soon as you get the appropriate value, just exit the loop. for example, you said that all you need is the first value on the internal map. so try something 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); 
0
source

Source: https://habr.com/ru/post/1235238/


All Articles