Payal
Payal

Reputation: 913

Android- GSON How to parse JSON Array with different data?

I have done rounds of JSON parsing but this is something that I have never come accross .How would we parse this kind of json Array?

 [{
"about": "xyz ",
"id": "cda",
"username": "ps"
}, {
"description": "this is sample response",
"id": "ahhj",
}]

Upvotes: 2

Views: 1101

Answers (5)

Dave Ranjan
Dave Ranjan

Reputation: 2984

Clearly, your json is not a list of homogeneous data. Hence, cannot be converted to List.

So, I tried to be in your shoes for a while, and created a json

[{"name":"dave","clazz":"V"},{"token":"VIW","type":"dexter"}]

and the best approach I could come up with

1: Convert it to JsonArray

JSONArray jsonArray = new JSONArray(json);

2: Since each object in array could of unique type, so until you are very sure about it keeping it as JsonObject is not that bad idea.

JsonObject jsonObject = jsonArray.getJSONObject(0);
String token = jsonObject.getString("token");

3: And for the cases when you are sure you have a Model (POJO) for the class you can definately to something like this.

MyPojo myPojo = new Gson().fromJson(jsonArray.getJSONObject(0).toString(), MyPojo.class);

Hope I helped! No! How about you tell me what I did wrong. :)

Upvotes: 6

digitaljoel
digitaljoel

Reputation: 26574

I would probably deserialize it into a Map<String,String>[] or if you are expecting other data types as values Map<String, Object>[] and traverse it that way as needed.

Upvotes: 1

Haniyeh Khaksar
Haniyeh Khaksar

Reputation: 804

your Json result to be a JsonObject that has Array of data. change your result data like below:

"data":{[
   {
    "about": "xyz ",
    "id": "cda",
    "username": "ps"
   },
   {
    "description": "this is sample response",
    "id": "ahhj",
   }
 ]}

then make a model class of this and use GSON. if you have any problem ask again.

Upvotes: 1

Helmi
Helmi

Reputation: 90

use jsonObject.had("key") to know if this key exist for this jsonObject. So you can identify your object from their unique key like in your example : if the object have the about key so it's like the first object and if it have description it's the second one. Make sure you iterate all JsonObject in the JsonArray

Upvotes: 1

Ruchira Randana
Ruchira Randana

Reputation: 4179

Maybe this answer might be of help.

Basically you should iterate each JSON object and use a GSON method to get hold of all the keys. Then you could iterate each keys and get the value using the key.

Upvotes: 1

Related Questions