我正在通过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
}
]
Run Code Online (Sandbox Code Playgroud)
这是将被使用的对象
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);
Run Code Online (Sandbox Code Playgroud)
构造的列表,它有10个对象,但问题是对象的所有数据成员都是null,我不会对此有什么不妥.实体是OrmDroid的实体类.
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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
您还可以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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6040 次 |
| 最近记录: |