如何从GSON解析中确定对象的类别? [英] How to determine class of object from GSON parse?
问题描述
我如何确定对象的类别?
Object objDeserialized = gson.fromJson(jsonFromString,Object.class);
//它可以是类型消息或RoomDetail
< blockquote>
gson.fromJson(jsonFromString,Object.class);
一般来说,这不会因为 Object.class
而工作。 Gson禁止重写 Object
类的反序列化并使用 ObjectTypeAdapter
(请参阅主 Gson
gson 2.8.0构造函数,可能更早):
$ b
//内置类型适配器不能被重写
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
factories.add(ObjectTypeAdapter.FACTORY);
//排除器必须位于处理用户定义类型的所有适配器之前
factories.add(excluder);
//用户类型适配器
factories.addAll(typeAdapterFactories);
如果您想使用 Object.class
,您必须将结果转换为原始包装, null
或映射< K,V>
- 并自行进行某种分析。它背后的基本原理是,你必须事先知道结果类,以确保你得到一个正确的反序列化的对象。
最好的你可以在这里做的事情是让你的自定义父超类型(真的不管它是一个类还是一个接口),比如 class Message扩展Base
和 class RoomDetail extends Base
,然后注册 JsonDeserializer< Base>
实现到 GsonBuilder $ c $它可以尝试检测
Base
实例的实际类型。之后,你可以这样做:
gson.fromJson(jsonSource,Base.class);
查看更多:
- 多态对象反序列化:
- 解析动态json和翻新2
- a href =https://stackoverflow.com/questions/43811168/how-do-i-parse-a-nested-json-array-of-object-with-a-custom-gson-deserializer/43818276#43818276 >如何使用自定义的Gson反序列化器分析嵌套的JSON数组对象?
li>谷歌Gson附加功能,从未发布为工件,但可能对您有启发意义:
I am parsing JSON string from a byte-array and casting it as an object.
How do I determine the class of the object?
Object objDeserialized = gson.fromJson(jsonFromString, Object.class);
//It could be type Message or RoomDetail
gson.fromJson(jsonFromString, Object.class);
In general, this won't work because of Object.class
. Gson prohibits overriding the Object
class deserialization and uses ObjectTypeAdapter
(see the primary Gson
constructor as of Gson 2.8.0 and probably much earlier):
// built-in type adapters that cannot be overridden
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
factories.add(ObjectTypeAdapter.FACTORY);
// the excluder must precede all adapters that handle user-defined types
factories.add(excluder);
// user's type adapters
factories.addAll(typeAdapterFactories);
If you want to use Object.class
, you have to cast the result to either a primitive wrapper, null
, or a List<E>
or Map<K,V>
-- and make some sort of analysis yourself. The rationale behind it is that you must know the result class in advance to make sure you're getting a proper deserialized object.
The best thing you can do here is making your custom parent super-type (does not really matter if it's a class or an interface), say class Message extends Base
and class RoomDetail extends Base
, and then registering a JsonDeserializer<Base>
implementation to a GsonBuilder
which can attempt to detect the real type of the Base
instance. After that you can do:
gson.fromJson(jsonSource, Base.class);
See more:
- Polymorphic objects deserialization:
- Google Gson extras, never been published as artifacts, but may be an inspiration point for you:
这篇关于如何从GSON解析中确定对象的类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!