Friday, April 27, 2018

Transient field initialization when using GSON

When you use GSON to deserialize a JSON string in your Java code, the class has to have a non-argument constructor in order for the transient fields to be initialized properly:


The output of the above code is as follows:

ClassWithImplicitNonArgConstructor
----------------------------------
json = {"val1":500}
value1 = 500
value3 = 3
intArray = [1, 2, 3]

ClassWithOnlyArgumentConstructor
--------------------------------
json = {"val1":1}
value3 = 0
intArray = null

ClassWithExplicitNonArgConstructor
----------------------------------
json = {"val1":1}
value3 = 3
intArray = [1, 2, 3]