Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing json array using gson?

I have my json as:

{
   "status": 200,
   "data": [
       {
            "catId": 638,
            "catName": "Helena Bonham Carter",
            "catUniqueName": "helena-bonham-carter",
            "catSlug": ""
       },
       {
        ...
       }
   ]
}

My Category model as:

public class Category {

    private double catId;
    private String catName;
    private String catUniqueName;
    private String catSlug;
}

And my gson custom deserializer is as follows:

Type listType = new TypeToken<ArrayList<Category>>(){}.getType();

Gson gson = new GsonBuilder()
            .registerTypeAdapter(listType, new CategoryDeserializer())
            .create();

private class CategoryDeserializer implements JsonDeserializer {
    @Override
    public Category deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        Gson gson = new Gson();
        return gson.fromJson(((JsonObject) json).get("data"), typeOfT);
    }
}

I am using Retrofit library which uses gson to serialize/deserialize json objects. I pass this custom gson deserializer to retrofit but it gives me an error. Can you tell me where I am going wrong while desrializing?

Error:

java.util.ArrayList cannot be cast to com.compzets.app.models.Category

Expected Result:

I want ArrayList of Category from json.

like image 614
Ram Patra Avatar asked Dec 27 '14 10:12

Ram Patra


1 Answers

Changing the return type of deserialize() from Category to ArrayList<Category> solved the issue. Rest of the code is correct.

like image 177
Ram Patra Avatar answered Sep 29 '22 07:09

Ram Patra