集合序列化问题

Collection serialization issues

所以我的问题有点复杂。我有一个用户 class,我将其放入 ConcurrentHashMap。一个class对应一个用户。密钥是用户的 ID。

我正在使用 GSON 序列化这个 ConcurrentHashMap 并保存我的用户的数据。

在用户 class 内部,我有多个变量(整数、字符串等)和几个集合。 问题在于覆盖文件。我的 4 个 ArrayList 中有 2 个像往常一样进行序列化,但是当我添加另一个 ArrayList 或与此相关的任何集合时,该集合将不会显示在文件中。但是,当我添加一个简单变量(如 String 或 Int)时,文件会更新并为每个用户附加这些值。创建新用户时,这些集合显示为没有任何反应。我需要为现有用户添加这些集合。

我的问题是为什么不能向 class 添加另一个 ArrayList,以及为什么它没有出现在文件中。

public class User {

private String nickname;
private String id;
private int coins;


  ...bunch of variables


private int bikes = 0;
private int scooters = 0;
private int goldIngots = 0;
private final ArrayList<Car> cars = new ArrayList<>(); //showing up
private final ArrayList<Hotel> hotels = new ArrayList<>(); //showing up
private final ArrayList<AwardType> awards = new ArrayList<>(); //not showing up   



...Constructor


...Getters And Setters

sample of UserClass

collections inside UserClass

how it should look

values are not appending

编辑

AwardType 是一个枚举。此包含 AwardType 的列表不会显示给现有用户,仅显示给新用户。

编辑 1

添加 Gson serializeNulls() 选项后,列表被添加到文件中,但为空。

"bikes": 0,
"scooters": 0,
"goldIngots": 0,
"cars": [],
"hotels": [],
"awards": null

如评论中所述,您需要向 class 添加一个无参数构造函数(有时也称为“默认构造函数”)。此构造函数可能是 private(因此您不会无意中调用它)。

Gson 需要此构造函数才能创建实例,然后在反序列化期间更新其字段值。其他带有参数的构造函数不起作用,因为 Gson 无法确定哪个 JSON 属性 与哪个构造函数参数匹配,并且假设参数的默认值(例如 0 和 null)可能不正确所有情况。

如果没有检测到无参数构造函数,Gson 使用特定的 JDK class 调用 sun.misc.Unsafe 来创建一个实例,而不调用任何构造函数并且不执行任何初始化块(包括初始化字段)。这可能会导致诸如您遇到的问题。此外,Unsafe class 可能并非在所有环境中都可用。因此,您应该避免依赖这种行为。

或者,您也可以为 class 创建一个 InstanceCreator,但在大多数情况下,添加无参数构造函数会更容易。