【问题标题】:How parse internal array json [duplicate]如何解析内部数组json [重复]
【发布时间】:2016-12-14 07:33:14
【问题描述】:

我有 json:

{
  "id": 1,
  "result": [
    {
      "id": 1,
      "imgUrl": "http://test.com/image.jpg",
      "title": "image"
    },
    {
      "id": 2,
      "imgUrl": "http://test.com/image2.jpg",
      "title": "image2"
    } 
  ],
  "jsonrpc": "2.0"
}

我如何解析内部数组,我尝试使用模型进行默认的 retroif gson 解析

public class TestRequest {

    public int id;
    public List<ArrayItems> result;
    public String jsonrpc;    
}

public class Item {

   public int id;
   public String imgUrl;
   public String title;
}

我有错误:预期为 BEGIN_OBJECT,但为 BEGIN_ARRAY。 然后我尝试手动解析

Item[] items = GSON.fromJson(json, Item[].class);

并且有错误:

应为 BEGIN_ARRAY,但为 BEGIN_OBJECT。

我们要做什么?

【问题讨论】:

    标签: java json gson retrofit


    【解决方案1】:

    主要问题是您的 POJO 中有一个 List&lt;Item&gt;,而您将 Item[].class 传递给解析器,但不匹配。

    Item[] items = GSON.fromJson(json, Item[].class);
    //                                 ↑ here!!!!
    

    无论如何,恕我直言,这不是您应该解析此 Json 的正确方法。

    • 您有一个包含 3 个标签(idresultjsonrpc)的主对象的 json 响应。
    • 您创建了类似 Java POJO 的东西来表示这个主要对象 (TestRequest)

    呜呜呜……

    使用它!

    据此,如果你解析主对象,你将拥有所有的 json 内容。

    TestRequest data = gson.fromJson(reader, TestRequest.class);
    

    现在,让我们测试一下,为了得到一个友好的输出,我用这种方式覆盖Item::toString()

    class Item {
    
        public int id;
        public String imgUrl;
        public String title;
        
        @Override
        public String toString() {
            return this.id + "-" + this.title;
        }
    }
    

    我使用main 方法进行了测试:

    final String FILE_PATH      = "C:\\tmp\\38830664.json"; // use your own!!!
    
    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new FileReader(FILE_PATH));
    TestRequest data = gson.fromJson(reader, TestRequest.class);
    
    for (Item i :data.result)
        System.out.println(i);
    

    输出:

    1-image
    2-image2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 2018-06-17
      • 2018-04-06
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 2021-09-25
      相关资源
      最近更新 更多