4

我正在通过 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 个对象,但问题是对象的所有数据成员都是空的,我不知道这有什么问题。Entity 是 OrmDroid 的 Entity 类。

4

2 回答 2

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;
}
于 2013-03-08T10:49:38.420 回答
-1

而不是List使用ArrayList

Gson gson = new Gson();
Type t = new TypeToken<ArrayList<MyBranch >>() {}.getType();     
ArrayList<MyBranch > list = (ArrayList<MyBranch >) gson.fromJson(json, t);
于 2013-03-08T10:48:17.990 回答