Viswam
Viswam

Reputation: 293

Extracting a specific element from a 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");

Upvotes: 3

Views: 1490

Answers (2)

objectorientedpeople
objectorientedpeople

Reputation: 11

May be u can make query over your json data using lambda expression.There is a class org.json.JSONarray using its getvalueas method and inside this method stream(your lambda ).filter(your lambda ).map(your lambda ) can solve your problem.

Thx

Upvotes: 0

azurefrog
azurefrog

Reputation: 10945

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

Upvotes: 5

Related Questions