【问题标题】:How to Parse json response using Gson Library in android?如何在 android 中使用 Gson 库解析 json 响应?
【发布时间】:2025-12-26 13:35:06
【问题描述】:

我有这样的 api 响应:

{
"0": "_serialize",
"1": [
    "login"
],
"users": {
    "token": "aaaaa",
    "message": "login successful."
    }
  }

如何在 android 中使用 Gson 解析这个?

【问题讨论】:

  • 需要通过Iterator来使用。
  • 你能给我举个例子吗?
  • 我认为可以使用模型类,但是使用动态键对于json格式并不理想,你可以用常量键替换“0”,“1”
  • 在此处使用this link 粘贴您的原始 JSON,在 Annotation Style 中选择 GSON,然后单击预览即可获取相关的 POJO 类。
  • 使用@AseemSharma 链接生成模型类,但如果“0”和“1”不是常量键,我会引起问题

标签: android json gson


【解决方案1】:

首先使用this one 等工具从您的json 中创建model 类。只需复制您的 json 并获取对象。

假设你调用类Model

然后使用 code 从您的 json 中获取 object

String json = "that-json";
Model m = gson.fromJson(json, Model.class);

更多关于Gson's guides

【讨论】:

    【解决方案2】:

    为你的 Json 创建一个 pojo。您可以使用许多在线资源,例如 thisthis

    现在使用下面的格式。

    Gson gson = new Gson();
    MyPojo myPojo = new MyPojo();
    Type collectionType = new TypeToken<MyPojo>() {
                        }.getType();
    myPojo = gson.fromJson(responseJson,
                                collectionType);
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      从响应中生成模型类

          public void onResponse(String response) {   
          JSONObject jsonObject = null;
          try {
              jsonObject = new JSONObject(response);
      
              YourModelClass objModel = gson.fromJson(jsonObject.getJSONObject("data").toString(), YourModelClass.class);
      
       } catch (JSONException e) {
          e.printStackTrace();
        }
      }
      

      【讨论】:

        【解决方案4】:

        使用 gson 并将您的响应映​​射到 Java 模型类。

        这将是你的模型类 ->

        User.java 模型类。

        import java.io.Serializable;
        import com.google.gson.annotations.Expose;
        import com.google.gson.annotations.SerializedName;
        import org.apache.commons.lang.builder.ToStringBuilder;
        
        public class Users implements Serializable
        {
        
            @SerializedName("token")
            @Expose
            private String token;
            @SerializedName("message")
            @Expose
            private String message;
            private final static long serialVersionUID = 3387741697269012981L;
        
            /**
             * No args constructor for use in serialization
             * 
             */
            public Users() {
            }
        
            /**
             * 
             * @param message
             * @param token
             */
            public Users(String token, String message) {
                super();
                this.token = token;
                this.message = message;
            }
        
            public String getToken() {
                return token;
            }
        
            public void setToken(String token) {
                this.token = token;
            }
        
            public Users withToken(String token) {
                this.token = token;
                return this;
            }
        
            public String getMessage() {
                return message;
            }
        
            public void setMessage(String message) {
                this.message = message;
            }
        
            public Users withMessage(String message) {
                this.message = message;
                return this;
            }
        
            @Override
            public String toString() {
                return new ToStringBuilder(this).append("token", token).append("message", message).toString();
            }
        
        }
        

        这是你的根/父类,从那里开始解析。

        import java.io.Serializable;
        import java.util.List;
        import com.google.gson.annotations.Expose;
        import com.google.gson.annotations.SerializedName;
        import org.apache.commons.lang.builder.ToStringBuilder;
        
        public class Root implements Serializable
        {
        
            @SerializedName("0")
            @Expose
            private String _0;
            @SerializedName("1")
            @Expose
            private List<String> _1 = null;
            @SerializedName("users")
            @Expose
            private Users users;
            private final static long serialVersionUID = 5880229946098431789L;
        
            /**
             * No args constructor for use in serialization
             * 
             */
            public Example() {
            }
        
            /**
             * 
             * @param users
             * @param _0
             * @param _1
             */
            public Example(String _0, List<String> _1, Users users) {
                super();
                this._0 = _0;
                this._1 = _1;
                this.users = users;
            }
        
            public String get0() {
                return _0;
            }
        
            public void set0(String _0) {
                this._0 = _0;
            }
        
            public Example with0(String _0) {
                this._0 = _0;
                return this;
            }
        
            public List<String> get1() {
                return _1;
            }
        
            public void set1(List<String> _1) {
                this._1 = _1;
            }
        
            public Example with1(List<String> _1) {
                this._1 = _1;
                return this;
            }
        
            public Users getUsers() {
                return users;
            }
        
            public void setUsers(Users users) {
                this.users = users;
            }
        
            public Example withUsers(Users users) {
                this.users = users;
                return this;
            }
        
            @Override
            public String toString() {
                return new ToStringBuilder(this).append("_0", _0).append("_1", _1).append("users", users).toString();
            }
        
        }
        

        现在在您接收 Json 映射 json 到解析开始的根/父类的代码处。

        Root root = new Gson().fromJson(/*put your json response variable here*/, Root.class);
        

        并使用根对象通过公共 get 方法获取/设置任何数据。

        【讨论】: