如何从GSON变量的值 [英] How to get variable's value from Gson
问题描述
首先,我是一个在begiiner所以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;
使用
林这些类检索与GSON库中的JSON。
Im using those class to retrieve the JSON with GSON library.
我成功地与这code检索JSON数据:
I successfully retrieve the JSON data with this code :
Gson gson = new Gson();
Response myResponse = gson.fromJson(inputStreamReader, Response.class);
当我调试code,我可以看到项目
类值中的 myResponse
。但是,我有一个问题,当我要访问标题
在项变量
类,因为我只有一个响应
类。
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.
在 如何获得
类? 标题
变量项目
任何帮助apprciated,感谢您的帮助。
Any help is apprciated, Thanks for your help.
推荐答案
如果您有公共
属性(通常的一个不好的做法),你可以这样做:
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;
}
无论如何,我说,你应该让你的属性私人
,并拥有的 getter和setter 的这些属性。这是Java的基础!
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;
}
在以同样的方式,你应该有私人
属性和getter和setter方法在各类课程。
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();
}
这篇关于如何从GSON变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!