Roger Travis Roger Travis - 2 years ago 141
Java Question

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

I'm trying to parse a JSON string like this one

"updated_at":"2012-03-02 21:06:01",
"fetched_at":"2012-03-02 21:28:37.728840",
"modified":"2012-03-02 23:28:58.840076"
"updated_at":"2012-03-02 14:07:44",
"fetched_at":"2012-03-02 21:28:37.033108",
"modified":"2012-03-02 23:28:57.928001"

into a list of objects.

List<channelSearchEnum> lcs = (List<channelSearchEnum>) new Gson().fromJson( jstring , channelSearchEnum.class);

Here's an object class I'm using.


public class channelSearchEnum {

private String updated_at;

private String fetched_at;

private String description;

private String language;

private String title;

private String url;

private String icon_url;

private String logo_url;

private String id;

private String modified;

public final String get_Updated_at() {
return this.updated_at;

public final String get_Fetched_at() {
return this.fetched_at;

public final String get_Description() {
return this.description;

public final String get_Language() {
return this.language;

public final String get_Title() {
return this.title;

public final String get_Url() {
return this.url;

public final String get_Icon_url() {
return this.icon_url;

public final String get_Logo_url() {
return this.logo_url;

public final String get_Id() {

public final String get_Modified() {
return this.modified;


But it throws me with java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

Any ideas how should I fix it?

Answer Source

The problem is you're telling Gson you have an object of your type. You don't. You have an array of objects of your type. You can't just try and cast the result like that and expect it to magically work ;)

The User guide for Gson Explains how to deal with this:

This will work:

channelSearchEnum[] enums = gson.fromJson(yourJson, channelSearchEnum[].class);

But this is better:

Type collectionType = new TypeToken<Collection<channelSearchEnum>>(){}.getType();
Collection<channelSearchEnum> enums = gson.fromJson(yourJson, collectionType);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download