Skip to content Skip to sidebar Skip to footer

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;

publicclassMyBranchextendsEntity {
    publicMyBranch() {
        super();
    }

    publicMyBranch(int id, String name, String isActive) {
        super();
        _ID = id;
        _Name = name;
        _Active = isActive;
    }

    @Column(name = "id", primaryKey = true)@SerializedName("ID")publicint _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;

publicclassMyBranchextendsEntity {
    publicMyBranch() {
        super();
    }

    publicMyBranch(int id, String name, String isActive) {
        super();
        ID = id;
        Name = name;
        Active = isActive;
    }

    @Column(name = "id", primaryKey = true)publicint ID;
    public String Name;
    public String Active;
}

Solution 2:

Instead of List use ArrayList ?

Gsongson=newGson();
Typet=newTypeToken<ArrayList<MyBranch >>() {}.getType();     
ArrayList<MyBranch > list = (ArrayList<MyBranch >) gson.fromJson(json, t);

Post a Comment for "Json Parsing With Gson Returns Null Object"