【发布时间】:2014-11-05 11:54:58
【问题描述】:
我正在尝试将 json 格式(来自 rest webservice 的 arraylist 响应)转换为相应的 java arraylist。
令人惊讶的是,3 个变量中只有 2 个被格式化为对象,3 个变量被设置为 null。
下面是字符串格式的json响应。
[{"points":"20","shares":"54","name":"Krishna"},{"points":"18","shares":"47","name":"Bhima"}]
我正在尝试使用以下代码转换为数组列表:
ArrayList<GplusFriend> gp_list;
Gson gson = new Gson();
gp_list = gson.fromJson(result, new TypeToken<List<GplusFriend>>(){}.getType());
Iterator itr = gp_list.iterator();
GplusFriend gf =null;
while(itr.hasNext()){
gf= (GplusFriend) itr.next();
Log.d("Restcall", "Name :"+gf.getName());
Log.d("Restcall", "points :"+gf.getPoints());
Log.d("Restcall", "shares :"+gf.getShares());
}
但我得到的日志是:
Name :null
points :20
shares :54
Name :null
points :18
shares :47
这是 GPlusFriend 的类定义:
public class GplusFriend {
String Name;
String points;
String shares;
public String getShares() {
return shares;
}
public void setShares(String shares) {
this.shares = shares;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPoints() {
return points;
}
public void setPoints(String points) {
this.points = points;
}
public GplusFriend(){
super();
}
public GplusFriend(String Name,String points,String shares){
super();
this.shares=shares;
this.Name = Name;
this.points = points;
}
@Override
public String toString(){
return this.Name + " "+this.points+" "+this.shares;
}
}
所以我在这里缺少什么..
【问题讨论】:
-
尝试在
GPlusFriend类中将Name更改为name。 -
或者,将
@SerializedName("name")添加到Name字段。这告诉 GSON 忽略字段名称并使用您指定的任何内容。甚至还有另一种方法,请参阅sites.google.com/site/gson/…