2013-03-08 220 views
4

我解析通过GSON JSON字符串,这是JSON字符串JSON解析与GSON返回null对象

[ 
{ 
    "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 
} 
] 

,这是将要useed

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的实体类。

回答

6

名称不匹配在您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

而不是List使用ArrayList?在MyBranch类中的字段的

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

它不与ArratList工作压力太大。 – Areff 2013-03-08 10:55:05

+0

是的......问题是你不使用'@ SerializedName',并且变量名称与JSON标签不同,请参阅@vmironov post。 – madlymad 2013-03-08 10:57:30