【问题标题】:Reading JSON with Retrofit使用 Retrofit 读取 JSON
【发布时间】:2014-03-20 04:28:50
【问题描述】:

我有以下 JSON 提要:

{
  collection_name: "My First Collection",
  username: "Alias",
  collection: {
     1: {
        photo_id: 1,
        owner: "Some Owner",
        title: "Lightening McQueen",
        url: "http://hesp.suroot.com/elliot/muzei/public/images/randomhash1.jpg"
        },
     2: {
        photo_id: 2,
        owner: "Awesome Painter",
        title: "Orange Plane",
        url: "http://hesp.suroot.com/elliot/muzei/public/images/randomhash2.jpg"
        }
    }
}

我要做的是获取集合的内容 - photo_id、所有者、标题和 URL。我有以下代码,但是我收到 GSON JSON 错误:

   @GET("/elliot/muzei/public/collection/{collection}")
    PhotosResponse getPhotos(@Path("collection") String collectionID);

    static class PhotosResponse {
        List<Photo> collection;
    }

    static class Photo {
        int photo_id;
        String title;
        String owner;
        String url;
    }
}

我认为我的代码对于获取 JSON 提要是正确的,但我不太确定。任何帮助表示赞赏。

我得到的错误是:

Caused by: retrofit.converter.ConversionException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 75

但是我很难理解如何使用 GSON 库

【问题讨论】:

  • 您收到什么样的错误?请问是Logcat吗?
  • 基本上,关键行是: 引起:retrofit.converter.ConversionException:com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期 BEGIN_ARRAY 但在第 1 行第 75 列是 BEGIN_OBJECT跨度>
  • 好的,所以我对 gson 并不是非常熟悉,但似乎它期待的是 Photos 的数组,而不是其中的 List
  • @K20GH 这是您正在解析的实际 JSON 吗?我不这么认为,因为Column 75 会在第一个photo_id 的中间。

标签: java android json retrofit


【解决方案1】:

您的 JSON 无效。

GSON 在collection: 之后等待BEGIN_ARRAY "[",因为您的PhotosResponse 类定义了一组照片List&lt;Photo&gt; 但找到了BEGIN_OBJECT "{",应该是

{
    "collection_name": "My First Collection",
    "username": "Alias",
    "collection": [
        {
            "photo_id": 1,
            "owner": "Some Owner",
            "title": "Lightening McQueen",
            "url": "http://hesp.suroot.com/elliot/muzei/public/images/randomhash1.jpg"
        },
        {
            "photo_id": 2,
            "owner": "Awesome Painter",
            "title": "Orange Plane",
            "url": "http://hesp.suroot.com/elliot/muzei/public/images/randomhash2.jpg"
        }
    ]
}

也许你从一个不正确的json_encode()带键的PHP数组中得到那个JSON,你应该从没有键的PHP中编码JSON,只用数组值(PHP Array to JSON Array using json_encode())

【讨论】:

  • 对,看起来应该是collection: [。但是,我仍然很好奇他的代码是否可以工作。
  • @user1923613 你好奇什么?
  • @JoshPinter,我认为 Retrofit GSON 可以直接获得“集合”键值对,而不受“colllection_name”和“username”的困扰。我遇到了同样的错误。我必须编写自己的 GSON 适配器才能正确使用,类似于此[链接](sachinpatil.com/blog/2012/07/03/gson)
猜你喜欢
  • 2014-03-14
  • 2015-12-24
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
  • 2016-08-13
  • 2022-01-21
相关资源
最近更新 更多