Type Information within serialized JSON using GSON

独自空忆成欢 提交于 2020-01-04 05:55:19

问题


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).

Is there a way to do this using GSON like:

{
    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.

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. How could implement is in such a generic way, that every object would be serialized with this property?


回答1:


You need to implement deserializer, which will look at the type property and cast objects to a given type. I believe, there is no other way.

Check out the javadoc, implementing this interface may be your answer.



来源:https://stackoverflow.com/questions/16213375/type-information-within-serialized-json-using-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!