Json Parsing With Gson Returns Null Object
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
Solution 1:
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;
}
Solution 2:
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);
Post a Comment for "Json Parsing With Gson Returns Null Object"