Google JSON,反序列化 class 并正确设置 class 字段值

Google JSON, Deserialize class and properly set class field values

如果 Gson 无法找到该特定元素,在保持默认 class 变量值的同时使用 Gson 反序列化对象的最佳方法是什么?

这是我的例子:

public class Example {

@Expose
public String firstName;
@Expose
public String lastName;
@Expose
public int age;

//Lets give them 10 dollars.
public double money = 10;

public Example(String firstName, String lastName, int age, double money) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.money = money;
}

public String getFirstName() {
    return firstName;
}

public String getLastName() {
    return lastName;
}

public int getAge() {
    return age;
}

public double getMoney() {
    return money;
}

}

主要class:

public class ExampleMain {

public static void main(String[] args) {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    Example example = new Example("John", "Doe", 24, 10000D);
    String json = gson.toJson(example);

    Example example2 = gson.fromJson(json,Example.class);
    System.out.println(example2.getMoney());
}

}

example2 的输出是 0.0,但不应该是 10.0,因为 class 已经定义了 10.0,我知道如果我也想序列化货币,我应该使用 Expose 注释,但主要问题如果将来添加更多 class 变量并且较旧的对象不包含 Money,会发生什么情况,它们将 return null、false 或 0 而不是它们的预设 class值。

谢谢。

您可能需要包含一个默认(无参数)构造函数,然后在主体中不初始化任何值,如下所示:

public Example(){ 
 //nothing goes on here...
}

Gson 反序列化到您的 POJO 时 - 它调用默认构造函数并将所有缺失值设置为 null0 (取决于类型) - 所以通过添加您自己的构造函数, Gson 将改为调用它。这就是当您包含默认构造函数时它现在可以工作的原因。 编码愉快。

只需向 Exmaple 添加一个无参数构造函数 class。它将强制 gson 开始使用 class.newInstance 创建对象,并且您将定期初始化 class (包括您的情况下 public 变量的正确值。)

添加一个无参数构造函数,它将被使用。

新实例的构造方法参考com.google.gson.internal.newUnsafeAllocator(?,?)

如果您的字段可以 static,您也可以这样做,gson 会在实例化您的 class 时不理会它,没有默认值 构造函数.