简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM