0

I have a JSON response representing a Band that looks like this:

[
 {
  "Picture": {
  "Small": "someurl
  "Medium": "someurl",
  "Large": "someurl",
  "XLarge": "someurl"
},
"Name": "Tokyo Control Tower",
"Guid": "TCT",
"ID": 15
 }
]

And I'm trying to use GSON to deserialize it into a class called SearchResults which contains a list of Bands. My SearchResults and Band classes look like this:

public class SearchResults {
    public List<Band> results;
}

public class Band {
    @SerializedName("Name")
    public String name;

    @SerializedName("Guid")
    public String guid;

    @SerializedName("ID")
    public Integer id;

    @SerializedName("Picture")
    List<Photo> pictures;

}

In my code I try to convert the json string like this:

protected void onPostExecute(String result) {
        Gson gson = new Gson();
        SearchResults results = gson.fromJson(result, SearchResults.class);
        Band band = results.results.get(0);
        bandName.setText(band.name);
    }

When I run this code, I get an error from GSON saying Expected BEGIN_OBJECT but was BEGIN_ARRAY. Any ideas on how to fix?

1
  • pictures is a list in your class definition (i.e. a JSON array), but it's a JSON object in the sample JSON you gave. Did you meant to either make it an array in the JSON, or create a "Pictures" class or map to represent the various picture sizes? Commented Aug 22, 2013 at 0:15

1 Answer 1

3

You have a couple issues.

First and foremost, what is causing the error you post is that you are telling Gson that your JSON represents an object (SearchResults) when it doesn't; your JSON is an array of objects (specifically, an object you're mapping to your Java Band class).

The correct way to do this is via:

Type collectionType = new TypeToken<Collection<Band>>(){}.getType();
Collection<Band> bands = gson.fromJson(jsonString, collectionType);

Once you do that you're going to have a problem in that in your Java class you're saying that "Picture" in your JSON is an array of Photo objects when in fact it's not; it's a single object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.