Androidicus
Androidicus

Reputation: 1748

Deserialize classes with same interface using GSON

I have an interface (called Content) and a couple of classes that implement that interface (e.g. ContentVideo, ContentAd...). I receive a JSON Object that contains a list of those objects. I started out deserializing those objects manually in seperate classes, but recently came across GSON, which would simplify this process immensely. But I'm not sure how to implement this.

Here's ContentVideoJSONParser

public ArrayList<ContentVideo> parseJSON(String jsonString) {
        ArrayList<ContentVideo> videos = new ArrayList<>();

        JSONArray jsonArr = null;
        Gson gson = new Gson();
        try {
            jsonArr = new JSONArray(jsonString);
            for(int i = 0; i < jsonArr.length(); i++) {
                JSONObject jsonObj = jsonArr.getJSONObject(i);
                ContentVideo cv = gson.fromJson(jsonObj.toString(), ContentVideo.class);
                videos.add(cv);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return videos;
    }

ContentAdJSONParser looks exactly the same, except for returning an ArrayList of ContentAd objects and this line to retrieve the object:

ContentAd ca = gson.fromJson(jsonObj.toString(), ContentAd.class);

What's the easiest way to combine those to classes into one? Note: one JSON object only contains one class, either ContentVideo or ContentAd. They are not mixed like in other SO questions, which would require a TypeAdapter.

This seems to be a straightforward problem but I can't figure it out. Thanks for your help.

Upvotes: 1

Views: 212

Answers (1)

t6nn
t6nn

Reputation: 91

Something like this perhaps?

public <T extends Content> ArrayList<T> parseJSON(String jsonString, Class<T> contentClass) {
    ArrayList<T> contents = new ArrayList<>();

    JSONArray jsonArr = null;
    Gson gson = new Gson();
    try {
        jsonArr = new JSONArray(jsonString);
        for(int i = 0; i < jsonArr.length(); i++) {
            JSONObject jsonObj = jsonArr.getJSONObject(i);
            T content = gson.fromJson(jsonObj.toString(), contentClass);
            contents.add(content);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return contents;
}

Upvotes: 1

Related Questions