首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Retrofit读取JSON

使用Retrofit读取JSON
EN

Stack Overflow用户
提问于 2014-02-20 01:03:14
回答 1查看 6.6K关注 0票数 4

我有以下JSON提要:

代码语言:javascript
复制
{
  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、owner、title和URL。我有以下代码,但是我得到了GSON JSON错误:

代码语言:javascript
复制
   @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提要,但是我不是很确定。感谢您的帮助。

我得到的错误是:

代码语言:javascript
复制
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库。

EN

回答 1

Stack Overflow用户

发布于 2014-02-20 02:28:12

您的JSON无效。

GSON正在等待collection:之后的BEGIN_ARRAY "[",因为您的PhotosResponse类定义了一个照片List<Photo>数组,但找到了一个BEGIN_OBJECT "{",它应该是

代码语言:javascript
复制
{
    "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"
        }
    ]
}

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21887318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档