0

I want to deserialize a Json with nested objects using the Gson library. I'm trying to get the data from the api of clash royale.

I've got the first Gson data printed on a TextView, but I'm finding it impossible to do the same with nested objects. Let me give you an example:

[
{
    "tag": "Whatever",
    "name": "Whatever",
    "trophies": 5262,
    "rank": 99,
    "arena": {
        "name": "Whatever",
        "arena": "Whatever",
        "arenaID": 14,
        "trophyLimit": 4700
    },
    "clan": {
        "tag": "Whatever",
        "name": "Whatever",
        "role": "Whatever",
        "donations": 23,
        "donationsReceived": 44,
        "donationsDelta": -20,
        "badge": {
            "name": "Whatever",
            "category": "Whatever",
            "id": 16003333,
            "image": "https://royaleapi.github.io/cr-api-assets/badges/Whatever.png"
        }

I can show the tag, the name and the trophies, but I am unable to access the data inside the clan object.

to print this data in TextView I simply declare a class where I host them, for example like this:

public class ClashData implements Serializable {

public String tag;
public String name;
public int trophies;

}

Then I connect it to TextView by placing a TextView in the corresponding layout and putting the following lines of code:

public ClashData data;

Afterwards, inside the onCreate

data =(ClashData)getIntent().getSerializableExtra("data");

And finally

    nameUser.setText("Name ", data.name);
    tagUser.setText("Tag " + data.tag);
    trophiesUser.setText("Trophies " + data.trophies);

I've tried everything to extract data from nested objects, but I don't know how to do it, can you help me?

Kote22
  • 27
  • 4

1 Answers1

0

You can modify Clan POJO as shown below:

public class Clan {
    @SerializedName("tag")
    @Expose
    public String tag;
    @SerializedName("name")
    @Expose
    public String name;
    @SerializedName("role")
    @Expose
    public int role;
    @SerializedName("donation")
    @Expose
    public int donations;


    /*Create getter and setter methods for all the instance variables.*/
}

Now add the above class to your ClashData as shown below:

public class ClashData  {
    @SerializedName("tag")
    @Expose
    public String tag;
    @SerializedName("name")
    @Expose
    public String name;
    @SerializedName("trophies")
    @Expose
    public int trophies;

    @SerializedName("clan")
    @Expose
    public Clan clanData; // add this line to your code

   /*Create getter and setter methods for all the instance variables.*/
}

Now you can use Gson library as shown below:

Gson gson = new Gson();
ClashData  data = gson.fromJson(jsonData,ClashData.class);
Clan clanData = data.getClanData();

Have referred to this while answering the question.

Yug Singh
  • 3,112
  • 5
  • 27
  • 52