Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a specific element from a JSON

Tags:

java

json

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");
like image 808
Vis Avatar asked Aug 05 '26 10:08

Vis


1 Answers

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");
like image 99
azurefrog Avatar answered Aug 07 '26 00:08

azurefrog