Search code examples
javagsonjson-deserialization

Google JSON, Deserialize class and properly set class field values


What would be the best way to deserialize an object with Gson while keeping default class variable values if Gson is unable to find that specific element?

Here's my example:

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;
}

}

The main 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());
}

}

The output of example2 is 0.0, but shouldnt that be 10.0 since the class has already defined 10.0, i know that i should use the Expose annotation if i want to serialise money too, but the main problem is what happens if in the future more class variables get added and older objects do not contain Money, they're going to return null, false or 0 instead of their pre-set class values.

Thanks.


Solution

  • You may need to include a default (no-args) constructor in which body you then do not initialize any values like this:

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

    When Gson deserializes into your POJO - it calls the default constructor and set all missing values to null or 0 (depending on type) - so by adding your own constructor, Gson will invoke it instead. This is why it works now when you include default constructor. Happy coding.