【问题标题】:Gson is not formatting one variable from json stringGson 没有从 json 字符串格式化一个变量
【发布时间】: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/…

标签: java json arraylist gson


【解决方案1】:

应该是

String name;

而不是

String Name;

您的 JSON 密钥是小写字母“名称” 使用 GSON 时,变量名区分大小写

【讨论】:

  • 它正在给出..您可以在 4 分钟内接受答案。一旦允许就会这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多