Looki Looki - 3 months ago 11
JSON Question

Nested Objects: Same Parent Object for multiple Child Objects

I am using Retrofit to fetch data from an API which returns JSON Objects in this format:

{
"error": 0
"message": "Request Successful"
"data": [ ... ]
}


I fetch it with GSON to POJO with these classes:

public class SearchResponse {
@SerializedName("error")
@Expose
private Integer error;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private List<SearchResult> data;

(Getter and Setter here)
}


public class SearchResult {
@SerializedName("name")
@Expose
private String name;
@SerializedName("id")
@Expose
private Integer id;
....

(Getter and Setter here)
}


The problem is, that for every request I make I have to make two new Classes, even though the outer Class always contains the same three Variables:
"error"
,
"message"
and
"data"
. Is there any way to use the same Parent for every child without completely removing it? (I still need the
"message"
field)

Answer

You can use generics:

public class SearchResponse<T> { // T is a type variable
    @SerializedName("error")
    @Expose
    private Integer error;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("data")
    @Expose
    private List<T> data; // We have a list of T

    (Getter and Setter here)
}

You would deserialize like:

Type t = new TypeToken<SearchResponse<SearchResult>>(){}.getType();
SearchResponse<SearchResult> response = gson.fromJson(jsonString, t);

You would still have to make a TypeToken for each child type though.