7

I am trying to serialize/deserialize JSON in Android using GSON. I have two classes that look like this:

public class Session {
@SerializedName("name")
private String _name;
@SerializedName("users")
private ArrayList<User> _users = new ArrayList<User>();
}

and:

public class User {
@SerializedName("name")
private String _name;
@SerializedName("role")
private int _role;
}

I am using GSON for serializing/deserializing the data. I serialize like so:

Gson gson = new Gson();
String sessionJson = gson.toJson(session);

This will produce JSON that looks like this:

{
"name":"hi",
    "users":
[{"name":"John","role":2}]
}

And I deserialize like so:

Gson gson = new Gson();
Session session = gson.fromJson(jsonString, Session.class);

I'm getting an error when I make this call.

DEBUG/dalvikvm(739): wrong object type: Ljava/util/LinkedList; Ljava/util/ArrayList;
WARN/System.err(739): java.lang.IllegalArgumentException: invalid value for field

I don't know what this error means. I don't see myself doing anything gravely wrong. Any help? Thanks!

1
  • 1
    Problem seems to go away when I change the users list in the Session class from an ArrayList to a List. Should this cause a problem for GSON? Commented Aug 23, 2011 at 12:45

1 Answer 1

13

Change your code to this:

  public class Session {
     @SerializedName("name")
     private String _name;
     @SerializedName("users")
     private List<User> _users = new ArrayList<User>();
  }

It's a good practice use Interfaces, and GSON requires that (at least, without extra configuration).

Gson converts the array "[ ]" in javascript, to a LinkedList object.

In your code, GSON tries to inject a LinkedList in the _users field, thinking than that field its a List.

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.