用gson解析Json返回null对象

时间:2013-03-08 10:43:10

标签: android json gson

我正在通过gson解析一个Json字符串,这是Json字符串

[
{
    "ID": 1,
    "Name": "Australia",
    "Active": true
},
{
    "ID": 3,
    "Name": "Kiev",
    "Active": true
},
{
    "ID": 4,
    "Name": "South Africa",
    "Active": true
},
{
    "ID": 5,
    "Name": "Stockholm",
    "Active": true
},
{
    "ID": 6,
    "Name": "Paris",
    "Active": true
},
{
    "ID": 7,
    "Name": "Moscow",
    "Active": true
},
{
    "ID": 8,
    "Name": "New York City",
    "Active": true
},
{
    "ID": 9,
    "Name": "Germany",
    "Active": true
},
{
    "ID": 10,
    "Name": "Copenhagen",
    "Active": true
},
{
    "ID": 11,
    "Name": "Amsterdam",
    "Active": true
}
]

这是将要使用的对象

public class MyBranch extends Entity {

public MyBranch () {
    super();
}

public MyBranch (int id, String name, String isActive) {
    super();
    _ID = id;
    _Name = name;
    _Active = isActive;
}

@Column(name = "id", primaryKey = true)
public int _ID;
public String _Name;
public String _Active;

}
Gson gson = new Gson();
Type t = new TypeToken<List<MyBranch >>() {}.getType();     
List<MyBranch > list = (List<MyBranch >) gson.fromJson(json, t);

构造的列表并且它有10个对象,但问题是对象的所有数据成员都是null,我不会对此有什么不妥。实体是OrmDroid的实体类。

2 个答案:

答案 0 :(得分:6)

MyBranch课程中字段的名称与json中的字段不匹配,因此您必须使用SerializedName注释。

import com.google.gson.annotations.SerializedName;

public class MyBranch extends Entity {
    public MyBranch () {
        super();
    }

    public MyBranch (int id, String name, String isActive) {
        super();
        _ID = id;
        _Name = name;
        _Active = isActive;
    }

    @Column(name = "id", primaryKey = true)
    @SerializedName("ID")
    public int _ID;

    @SerializedName("Name")
    public String _Name;

    @SerializedName("Active")
    public String _Active;
}

修改 您还可以通过简单重命名SerializedName字段来避免使用MyBranch注释:

import com.google.gson.annotations.SerializedName;

public class MyBranch extends Entity {
    public MyBranch () {
        super();
    }

    public MyBranch (int id, String name, String isActive) {
        super();
        ID = id;
        Name = name;
        Active = isActive;
    }

    @Column(name = "id", primaryKey = true)
    public int ID;
    public String Name;
    public String Active;
}

答案 1 :(得分:-1)

而不是List使用ArrayList

Gson gson = new Gson();
Type t = new TypeToken<ArrayList<MyBranch >>() {}.getType();     
ArrayList<MyBranch > list = (ArrayList<MyBranch >) gson.fromJson(json, t);