Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON Deserializing transients as null

Tags:

java

json

gson

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.

like image 352
Dustin Avatar asked May 10 '26 15:05

Dustin


1 Answers

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.

like image 65
Dustin Avatar answered May 12 '26 06:05

Dustin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!