user3077388
user3077388

Reputation: 23

Gson nested objects within nested objects

I know this question has been brought up quite often, but so far I didn't really find an answer which helped me solve my problem (I tried some of them).

Basically I'm getting a JSON-Response from this API http://api.tvmaze.com/singlesearch/shows?q=izombie&embed=episodes and there are quite a few nested objects within nested objects. For example taking a look at it with a JSON online viewer gives me the following output: What's interesting for me is the bottom part. To be more specific the "episodes" object. So far I can extract basic informations from the JSON-Array (id, url, name, type,...) but can not get the "triple (_embedded > episodes > ...)" nested objects.

The code to parse the JSON-Response:

public void parseJSON(String jsonResponse) throws IOException {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    Show show = gson.fromJson(jsonResponse, Show.class);
    System.out.println(show.getID() + "\n" + show.getName() + "\n" + show.getStatus());
}

The Show class:

public class Show {
    private int id;
    private String name;
    private String status;


    public int getID() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getStatus() {
        return status;
    }
}

So how would I get all those informations from 0 till the end at the episodes array? Any help is much appreciated!

On a side note: I'm getting the jsonResponse with a method called "readUrl" but it's pretty much irrelevant right now.

Upvotes: 0

Views: 584

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93613

GSON handles embedded objects just fine. Lets say you have a class Foo with a Bar embedded, you'd just do

class Foo {
   public Bar bar;
}

and it will parse bar for you. And that works recursively. If you need an array, use a List<Bar> and it will parse the array.

Upvotes: 1

Related Questions