Json parsing with gson returns null object

前端 未结 2 547
终归单人心
终归单人心 2021-01-19 09:40

I am parsing a Json string via gson , this is the Json string

[
{
    \"ID\": 1,
    \"Name\": \"Australia\",
    \"Active\": true
},
{
    \"ID\": 3,
    \"         


        
相关标签:
2条回答
  • 2021-01-19 10:06

    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;
    }
    
    0 讨论(0)
  • 2021-01-19 10:08

    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);
    
    0 讨论(0)
提交回复
热议问题