GSON反序列化自定义对象数组

时间:2022-06-12 17:07:15

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

我正在尝试使用GSON在Android中序列化/反序列化JSON。我有两个看起来像这样的类:

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 gson = new Gson();
String sessionJson = gson.toJson(session);

This will produce JSON that looks like this:

这将生成如下所示的JSON:

{
"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


11  

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).

使用Interfaces是一个很好的做法,GSON要求(至少没有额外的配置)。

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

Gson将javascript中的数组“[]”转换为LinkedList对象。

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

在您的代码中,GSON尝试在_users字段中注入一个LinkedList,并认为该字段是一个List。

#1


11  

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).

使用Interfaces是一个很好的做法,GSON要求(至少没有额外的配置)。

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

Gson将javascript中的数组“[]”转换为LinkedList对象。

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

在您的代码中,GSON尝试在_users字段中注入一个LinkedList,并认为该字段是一个List。