GSON Deserializing Transients As Null
I have a POJO with a field marked as transient. GSON does not serialize it. Fine. But when it deserializes, it wipes out the initial field settings.
For example, if I have this object:
public class ObjWithTransient {
public String name;
public transient List<String> listOStrings = new ArrayList();
}
And I am running this test:
@Test
public void testSerializeWithTransient() throws Exception {
ObjWithTransient obj = new ObjWithTransient();
obj.name = "Foobar";
String json = gson().toJson(obj);
// Deserialize
ObjWithTransient obj2 = GsonUtil.gson().fromJson(json, ObjWithTransient.class);
Assert.assertEquals(obj2.name, "Foobar");
Assert.assertNotNull(obj2.listOStrings); // <--- Fails here
Assert.assertEquals(obj2.listOStrings.size(), 0);
}
In noting this transient, I am assuming that I am telling GSON to ignore it, but that does not seem to be the case. What's the best way to keep the initial settings here?
EDIT: I believe the problem is that there is no declared constructor. This does not work with an inner class, but it does work with a regular class or static inner class. Reading the GSON code, it tries to create multiple ways to create the object, but ends up using UnsafeConstructor to create it if nothing else works. This creates an object with zero entries across the entire board. I could also add an InstanceCreator to tell Gson how to create the object.
source to share
I believe the problem is that there is no declared constructor. This does not work with an inner class, but it does work with a regular class or static inner class. Reading the GSON code, it tries to create multiple ways to create the object, but ends up using UnsafeConstructor to create it if nothing else works. This creates an object with zero entries across the entire board. I could also add an InstanceCreator to tell Gson how to create the object.
source to share