【问题标题】:Read JSONArray from JSONObject using GSON Android使用 GSON Android 从 JSONObject 读取 JSONArray
【发布时间】:2015-07-22 12:01:41
【问题描述】:

如何使用 GSON 从 JSONObject 读取 JSONArray。

我正在尝试读取这个 JSON 字符串:

String str  = { "text" : [ 
    {
        "id": 1,
        "msg":"abc"

    },
    {
        "id": 2,
        "msg":"xyz"

    },
    {
        "id": 3,
        "msg":"pqr"

    }

    ] }

班级是:

Class A {
    int id;
    String msg;
    // And setters and getters
}

此代码不起作用:

class Test {
            A [] text; 
        }

        Test t = gson.fromJson(response, Test.class);

        Also
        class Test {
            ArrayList<A> text =  new ArrayList<A>(); 
        }

        Test t = gson.fromJson(response, Test.class);

我还能如何使用我的测试类读取字符串?

请帮忙...

【问题讨论】:

  • 使用 jsonschema2pojo.org 为您的 json 响应创建 pojo 类,并将其作为 gson.fromJson(response, Pojo.class); 传递到您的代码中;
  • 您需要进一步的帮助吗?

标签: android json gson


【解决方案1】:

更新你的课程

public class A {
    @SerializedName("id")
    int id;

    @SerializedName("msg")
    String msg;
    // And All setter and getter

}

【讨论】:

    【解决方案2】:

    作为“JSON 字符串”给出的值是启动 A 类的值。它们是As 的数组。什么可能有效

        A[] t = gson.fromJson(response, A[].class);
    

    the manual, 5.4 Array Examples 中描述了反序列化数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      相关资源
      最近更新 更多