使用GSON在序列化JSON中输入类型信息 [英] Type Information within serialized JSON using GSON

查看:330
本文介绍了使用GSON在序列化JSON中输入类型信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Jackson,我们可以选择将类型信息附加到序列化对象(

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

是否可以使用GSON来做到这一点?

Is there a way to do this using GSON like:

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

这个想法是让它具有通用性,因此当反序列化ArrayList<Object>时,将使用它还原正确的对象实例.

The idea is to have it generic, so when a ArrayList<Object> is deserialized, the right object instances are restored with it.

我看到了这个问题: https://stackoverflow.com/a/8683689/1001027 或多或少我需要的东西,但仅适用于特定类别的对象.如何以一种通用的方式实现,即每个对象都将使用此属性进行序列化?

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?

推荐答案

您需要实现解串器,该解串器将查看type属性并将对象转换为给定类型.我相信,别无他法.

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.

查看 javadoc ,实现此界面可能是您的答案.

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

这篇关于使用GSON在序列化JSON中输入类型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆