0

I tried this solution : Parse Dynamic Key Json String using Retrofit but not got the proper solution

input data is :

{
    "details": {
        "10": [{
            "id": "1",
            "name": "sample_data1"
        }, {
            "id": "2",
            "name": "sampledata_2"
        }]
    }
}

I want to parse this json object with the unkwon keys

letsCode
  • 2,774
  • 1
  • 13
  • 37
Siddhesh Pawar
  • 259
  • 4
  • 24

2 Answers2

1

This should get you started

    JSONObject details = new JSONObject("details");
    Iterator keys = details.keys();

    while(keys.hasNext()) {
        // loop to get the dynamic key
        String dynamicKeys = (String)keys.next();

        // get the value of the dynamic key
        JSONObject dynamicValue = details.getJSONObject(dynamicKeys);

        // do something here with the value...
    }
letsCode
  • 2,774
  • 1
  • 13
  • 37
1

you can do something like this using GSON

JsonObject detailsJson = new JsonParser("JsonString").getAsJsonObject();
List<SomeObject> list = new ArrayList<>();
Gson gson = new Gson();
for(Map.Entry<String,JsonElement> jsonMap: detailsJson.entrySet()){
    //get the json array or 
    //jsonMap.getValue().getAsJsonArray();  do something else
    //or parse it to some model
    SomeModel obj = gson.fromJson(jsonMap.getValue(),SomeModel.class);
    list.add(obj);

}
vikas kumar
  • 10,447
  • 2
  • 46
  • 52