Reputation: 1642
I am parsing a Json string via gson , this is the Json string
[
{
"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
}
]
and this is the Object which is going to be 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);
the list constructed and it has 10 object , but the problem is all of object's data members is null, i dont no what's wrong with this. The Entity is OrmDroid's Entity class.
Upvotes: 4
Views: 6119
Reputation: 30864
Names of the fields in your MyBranch
class don't match to the fields in your json
so you have to use SerializedName
annotation.
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;
}
EDIT:
You can also avoid using SerializedName
annotation by simple renaming MyBranch
fields:
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;
}
Upvotes: 6
Reputation: 6530
Instead of List
use ArrayList
?
Gson gson = new Gson();
Type t = new TypeToken<ArrayList<MyBranch >>() {}.getType();
ArrayList<MyBranch > list = (ArrayList<MyBranch >) gson.fromJson(json, t);
Upvotes: -1