[英]GSON Deserializing transients as null
I have a POJO with a field marked as transient. 我有一个标有瞬态字段的POJO。 GSON does not serialize it. GSON没有将其序列化。 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. 通过标记它是暂时的,我假设我告诉GSON忽略它,但似乎并非如此。 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. 阅读GSON代码,它尝试了多种创建对象的方法,但最终使用UnsafeConstructor来创建它,如果没有其他工作。 This creates an object with null entries across the board. 这将创建一个具有全部空条目的对象。 I could also add an InstanceCreator to tell Gson how to create the object. 我还可以添加一个InstanceCreator来告诉Gson如何创建对象。
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. 阅读GSON代码,它尝试了多种创建对象的方法,但最终使用UnsafeConstructor来创建它,如果没有其他工作。 This creates an object with null entries across the board. 这将创建一个具有全部空条目的对象。 I could also add an InstanceCreator to tell Gson how to create the object. 我还可以添加一个InstanceCreator来告诉Gson如何创建对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.