Steve Kamau Steve Kamau - 1 month ago 8
Android Question

How to use For loop or While loop parsing JSONObjects

Currently I am using an Iterator loop to parse my JSON objects. Works well for a small to medium dataset. But when my dataset increases, so does the performance time. For example:



//groupedData is my JSONObject dataset
Iterator<String> iter = groupedData.keys();
int i = 0;
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = groupedData.get(key);
//add the value to an entry
values_1.add(new Entry(Float.valueOf(String.valueOf(value)), i));
//add key to an arraylist
labels_1.add(key);
} catch (JSONException e) {
// Something went wrong!
}
i++;
}





I used these Iterator loops for like 4 more different datasets. It ends up taking forever to loop through everything.

After digging, I got this lead which showed results show that the Iterator mechanism is the slowest method to loop through a list. There's not much performance difference between the For and the While loop.

So is there a better way to loop through JSON Objects using the For or WHile loops?

My JSONObject data is like:



{
"Admin": 19900,
"James": 2000,
"Steve": 1501,
"Linda": 3840,
"Grace": 2170,
"Jeff": 1200,
"Carolle": 350
}





Any suggestions?

Answer

Use GSON to parse the JSON.

Try this,

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = new Gson().fromJson(groupedData.toString(), type);
Comments