Blaze Tama
Blaze Tama

Reputation: 10948

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<Item> items;

class Item
  String id;
  String title;
  Private Player;

class Player
  String mobile;

Im using those class to retrieve the JSON with GSON library.

I successfully retrieve the JSON data with this code :

Gson gson = new Gson();
Response myResponse = gson.fromJson(inputStreamReader, Response.class);

When i debug the code, i can see the Item class value is successfully retrieved inside the myResponse. However, i have a problem when i want to access the title variable in the Item Class because all i have is a Response Class.

How to get the title variable in the Item Class?

Any help is apprciated, Thanks for your help.

Upvotes: 1

Views: 1513

Answers (2)

MikO
MikO

Reputation: 18741

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

//This will iterate over all items
for (Item item : myResponse.data.items) {
    //for each item now you can get the title
    String title = 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(){
    return this.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 method
Data data = myResponse.getData();
for (Item item : data.getItems()) {
    String title = myItem.getTitle();
}

Upvotes: 2

Rahul
Rahul

Reputation: 45060

You can fetch the data like this:-

Data myData = 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.

Upvotes: 2

Related Questions