I have a JSON as folows
{
"Root1": {
"Result": {
"ID": "200",
"Text": "OK"
}
}
}
Is there any way I can able to extract the values of "ID" to a variable directly without traversing through the root element i.e. "Root1". Because the root element name will change each time I run the application like "Root2", "Root3".
Below is the code in which I am trying to extract the ID with "Root1" and "Result" element
JSONObject jsonObject = new JSONObject("{\"Root1\": {\"Result\": {\"ID\": \"200\",\"Text\": \"OK\"}}}");
String element = jsonObject.getJSONObject("Root1").getJSONObject("Result").getString("ID");
As long as the structure of the json is always consistent, you can just get all the keys from the root object, and use the first key found to access the ID:
JSONObject jsonObject = new JSONObject("{\"Root1\": {\"Result\": {\"ID\": \"200\",\"Text\": \"OK\"}}}");
String rootKey = (String)jsonObject.keys().next();
String element = jsonObject.getJSONObject(rootKey).getJSONObject("Result").getString("ID");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With