Salah Owaidah Salah Owaidah - 1 month ago 21
JSON Question

Parsing JSON String Android

how can i parse such JSON string (but i have dynamic values)

{
"data":{
"dynamicValue1":{
"serial":"1",
"name":"ABC"
},
"dynamicValue2":{
"serial":"2",
"name":"DEF"
},
"dynamicValue3":{
"serial":"3",
"name":"GHI"
}
}
}


most codes i saw before for static values, but i want help please thanks in advance.

Answer

I suggest Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.

according to your json string code must be something look like this:-

//refers to the current element in the array "data"
JSONObject mainObj = new JSONObject(yourString);
JSONObject dynamicValue1 = mainObj.getJSONObject("dynamicValue1");
Iterator key = dynamicValue1.keys();

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

    //get value of the dynamic key
    JSONObject currentDynamicValue = dynamicValue1.getJSONObject(currentDynamicKey);

    // here do something  with the other value...
}

I suggest to you can try this solution.