Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 207
erik Avatar asked Nov 04 '15 20:11

erik


People also ask

How do I find the first value of JSON object?

The Object. values() will return an only array of values available in an object, now we can easily get the first value from the JSON object using array 0th index.

How do you get the values of the different types from a JSON object in Java?

A JSONObject has few important methods to display the values of different types like getString() method to get the string associated with a key string, getInt() method to get the int value associated with a key, getDouble() method to get the double value associated with a key and getBoolean() method to get the boolean ...

Does JSON object maintain order?

The JSON Data Interchange Standard definition at json.org specifies that “An object is an unordered [emphasis mine] set of name/value pairs”, whereas an array is an “ordered collection of values”. In other words, by definition the order of the key/value pairs within JSON objects simply does not, and should not, matter.

How do you find the value of JsonNode?

We can access a field, array or nested object using the get() method of JsonNode class. We can return a valid string representation using the asText() method and convert the value of the node to a Java int using the asInt() method of JsonNode class.


1 Answers

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);
like image 116
ρяσѕρєя K Avatar answered Oct 21 '22 14:10

ρяσѕρєя K