4

我有以下 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 库

4

1 回答 1

5

您的 JSON 无效。

GSON 正在等待,BEGIN_ARRAY "["因为collection:您的PhotosResponse类定义了一个 Photo 数组List<Photo>但找到了一个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()

于 2014-02-19T18:28:12.130 回答