简体   繁体   English

使用GSON在序列化JSON中输入类型信息

[英]Type Information within serialized JSON using GSON

Using Jackson we have the option to attach the type info to the serialized object ( http://jackson.codehaus.org/1.5.5/javadoc/org/codehaus/jackson/annotate/JsonTypeInfo.html ). 使用Jackson,我们可以选择将类型信息附加到序列化的对象上( http://jackson.codehaus.org/1.5.5/javadoc/org/codehaus/jackson/annotate/JsonTypeInfo.html )。

Is there a way to do this using GSON like: 有没有办法像这样使用GSON来做到这一点:

{
    propertyName:"test",
    _className:"foo.bar.TestClass"
}

The idea is to have it generic, so when a ArrayList<Object> is deserialized, the right object instances are restored with it. 想法是让它具有通用性,因此当ArrayList<Object>被反序列化时,正确的对象实例将随之恢复。

I saw this question: https://stackoverflow.com/a/8683689/1001027 that is more or less what I need but it works just for a specific class of objects. 我看到了这个问题: https : //stackoverflow.com/a/8683689/1001027或多或少是我所需要的,但是它仅适用于特定类别的对象。 How could implement is in such a generic way, that every object would be serialized with this property? 如何以一种通用的方式实现每个对象都将使用此属性进行序列化?

You need to implement deserializer, which will look at the type property and cast objects to a given type. 您需要实现解串器,该解串器将查看type属性并将对象转换为给定类型。 I believe, there is no other way. 我相信,没有其他办法。

Check out the javadoc , implementing this interface may be your answer. 查看javadoc ,实现此接口可能是您的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM