Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON Deserializing Array of Custom Objects

Tags:

json

android

gson

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!

like image 304
Patrick D Avatar asked Aug 23 '11 11:08

Patrick D


1 Answers

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.

like image 99
Imaky Avatar answered Oct 23 '22 07:10

Imaky