Let's say we have a structure like this:
JSON:
{ "body": { "cats": [ { "cat": { "id": 1, "title": "cat1" } }, { "cat": { "id": 2, "title": "cat2" } } ] } }
And the corresponding POJO:
Response.class
private final Body body;
Body.class
private final Collection<CatWrapper> cats
CatWrapper.class
private final Cat cat
Cat.class
private final int id; private final String title;
But suppose now we have the same structure, but instead of Cat we get truck
{ "body": { "trucks": [ { "truck": { "id": 1, "engine": "big", "wheels": 12 } }, { "truck": { "id": 2, "engine": "super big", "wheels": 128 } } ] } }
I use GSON (default Retrofit json parser) on Android , keep this in mind when offering solutions.
We could use generics here to make the answer look like this:
private final Body<ListResponse<ItemWrapper<T>> but we cannot, as field names are class specific.
QUESTION:
What can I do to serialize it automatically without creating as many template classes? I don't need separate classes like BodyCat , BodyTruck , BodyAnyOtherClassInThisStructure and I'm looking for a way to avoid them.
@EDIT:
I changed the classes (cat, dog → cat, truck) due to the confusion of inheritance, the classes used here as an example DO NOT extend each other
java json android generics gson
Than
source share