Json parsing with gson returns null object

前端 未结 2 546
终归单人心
终归单人心 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;
    }
    

提交回复
热议问题