Dustin
Dustin

Reputation: 397

GSON Deserializing transients as null

I have a POJO with a field marked as transient. GSON does not serialize it. Great. But when it is deserialized it wipes out the the field's initial settings.

For example, if I have this object:

public class ObjWithTransient {
    public String name;
    public transient List<String> listOStrings = new ArrayList();
}

And I run 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);
}

By marking it transient, I assume I am telling GSON to ignore it, but that doesn't seem to be the case. What is the best way to retain the initial settings here?

EDIT: I believe the issue is because there is not a declared constructor. This does not work with an inner class, but with a normal class or a static inner class it appears to work. Reading the GSON code, it trys multiple ways to create the object, but ultimately uses a UnsafeConstructor to create it if nothing else works. This creates an object with null entries across the board. I could also add an InstanceCreator to tell Gson how to create the object.

Upvotes: 3

Views: 981

Answers (1)

Dustin
Dustin

Reputation: 397

I believe the issue is because there is not a declared constructor. This does not work with an inner class, but with a normal class or a static inner class it appears to work. Reading the GSON code, it trys multiple ways to create the object, but ultimately uses a UnsafeConstructor to create it if nothing else works. This creates an object with null entries across the board. I could also add an InstanceCreator to tell Gson how to create the object.

Upvotes: 1

Related Questions