K20GH
K20GH

Reputation: 6281

Reading JSON with Retrofit

I've got the following JSON feed:

{
  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"
        }
    }
}

What I am trying to do is get the contents of the collection - photo_id, owner, title and URL. I have the following code, however I am getting GSON JSON errors:

   @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;
    }
}

I thought my code was correct to get the JSON feed, however I'm not so sure. Any help appreciated.

The error I get is:

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

However I'm struggling to understand how to use the GSON library

Upvotes: 4

Views: 6653

Answers (1)

vzamanillo
vzamanillo

Reputation: 10554

Your JSON is not valid.

GSON is waiting for a BEGIN_ARRAY "[" after collection: because your PhotosResponse class define an array of Photo List<Photo> but found a BEGIN_OBJECT "{", it should be

{
    "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"
        }
    ]
}

maybe you get that JSON from an incorrect json_encode() PHP array with key, you should encode JSON from PHP without keys, with the array values only (PHP Array to JSON Array using json_encode())

Upvotes: 5

Related Questions