我想將json格式(來自rest webservice的arraylist響應)轉換爲相應的java arraylist。Gson沒有從json字符串格式化一個變量
令人驚訝的是,3個變量中只有2個被格式化爲對象,3個變量被設置爲null。
下面是字符串格式的json響應。
[{"points":"20","shares":"54","name":"Krishna"},{"points":"18","shares":"47","name":"Bhima"}]
我想轉換與下面的代碼的ArrayList:
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'。 – Rohan 2014-11-05 12:01:03
或者,將'@SerializedName(「name」)'添加到'Name'字段。這告訴GSON忽略字段名稱並使用您指定的任何內容。還有另一種方法,請參閱https://sites.google.com/site/gson/gson-user-guide#TOC-JSON-Field-Naming-Support – zapl 2014-11-05 12:06:02