简体   繁体   中英

Get values of jsonarray using other jsonarray values as a key

I'm getting following json from server:

{
"Data": [
    {
        "Record": [
            " d11",
            "d12"
        ]
    },
    {
        "Record": [
            " d21",
            "d22"
        ]
    }
],
"Keys": [
    "Key1",
    " key2"
]

}


I want to retrieve record values which are ordered with respect to keys values(key1, key2?

Note: Using org.json api only.

Your question is still a little unclear to me, but I'm assuming you want to turn that JSON into a list of records, where each record is (for example) a map containing the keys from the list of keys and the values from the data list.

In order to achieve this, we first parse the JSON into a JSONObject :

String json = " ... ";
JSONTokener tokener = new JSONTokener(json);
JSONObject jsonObject = new JSONObject(tokener);

Then we extract the list of keys and the data list:

JSONArray data = jsonObject.getJSONArray("Data");
JSONArray keys = jsonObject.getJSONArray("Keys");

and define a list to contain our output:

List<Map<String, String>> records = new ArrayList<>();

Finally, we iterate over the data list, extract the list of record values for each item in that list, and then iterate over the keys in order to create a map from key to record value:

for (int i = 0; i < data.length(); i++) {
    JSONObject dataItem = data.getJSONObject(i);
    JSONArray recordValues = dataItem.getJSONArray("Record");

    Map<String, String> record = new HashMap<>();

    for (int j = 0; j < keys.length(); j++) {
        String key = keys.getString(j);
        String value = recordValues.getString(j);
        record.put(key, value);
    }

    records.add(record);
}

When we then print the value of records , we get something that looks like:

[{Key1= d11,  key2=d12}, {Key1= d21,  key2=d22}]

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