Deserializing Array of Arbitrary Objects

I am trying to serialize / deserialize JSON on 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 use GSON to serialize / deserialize data. I serialize like this:

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

This will result in a JSON that looks like this:

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

And I deserialize like this:

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

I get an error when making 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 do not know what this error means. I don’t see that I am doing something serious. Any help? Thank you

+7
source share
1 answer

Change the code as follows:

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

Good practice uses interfaces, and GSON requires (at least without additional configuration).

Gson converts the javascript array "[]" into a LinkedList object.

In your code, GSON is trying to enter LinkedList in the _users field, thinking of its list on this field.

+11
source

All Articles