Tuesday, February 10, 2015

Expected a string but was BEGIN_ARRAY at line 1 column - Gson

Expected a string but was BEGIN_ARRAY at line 1 column 

I was receiving "Expected a string but was BEGIN_ARRAY at line 1 column" error while deserializing the json string to java object using Gson.

Model class:

public class EmailGroup{
private String type;
private String id;
private String name;
private String permissions;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPermissions() {
return permissions;
}
public void setPermissions(String permissions) {
this.permissions = permissions;
}
}

JSON Response:

{"emailGroup":{"type":"EmailGroup","id":"1","depth":"minimal","description":"","name":"sample","permissions":[2,5,4,3]}}

Gson gson = new Gson();
EmailGroup obj = gson.fromJson(jsonstring, EmailGroup.class)

The root cause of the exception is the permissions attribute defined in the model class is of type String but the type of permissions in the jsonstring is List.

To fix the issue convert the type of permissions in the model class to List<String>(type string will change based on the type of the list entries)

public class EmailGroup{
private String type;
private String id;
private String name;
private List<String> permissions;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPermissions() {
return permissions;
}
public void setPermissions(List<String> permissions) {
this.permissions = permissions;
}
}



1 comment:

  1. After hours of reviewing StackOverFlow and all manner of documentation, this was my issue, thanks for the post.

    ReplyDelete