Skip to content Skip to sidebar Skip to footer

How To Get Variable's Value From Gson

First, im a begiiner in GSON so please bear with me. I have a set of classes with this structure : class Response Data data; class Data List items; class Item S

Solution 1:

If you have public attributes (which is usually a bad practice!) you can just do:

//This will iterate over all itemsfor (Item item : myResponse.data.items) {
    //for each item now you can get the titleStringtitle= myItem.title;
}

Anyway, as I said, you should make your attributes private, and have getters and setters for those attributes. That's Java basics!

Namely, in your Response class, you should have something like:

private Data data;

public Data getData(){
    returnthis.data;
}
public void setData(Data data){
    this.data = data;
}

In the same way, you should have private attributes and getters and setters in all your classes.

So now you can access your items in the proper way with:

//Get the Data object with the getter methodDatadata= myResponse.getData();
for (Item item : data.getItems()) {
    Stringtitle= myItem.getTitle();
}

Solution 2:

You can fetch the data like this:-

DatamyData= myResponse.getData();
for(Item myItem : myData.getItems()){
    // myItem.getTitle(); will give you the title from each Item
}

This is assuming that you've getters for all the fields in the classes.

Post a Comment for "How To Get Variable's Value From Gson"