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.
Changing the return type of deserialize() from Category to ArrayList<Category> solved the issue. Rest of the code is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With