GSON反序列化:如何知道对象? [英] GSON deserialization : how to know the objects?
问题描述
我尝试使用gson库来反序列化发送给我的对象流。
在我看到的所有示例中,当调用Json的方法时,我们已经知道我们期望的对象类型。
在我的情况中,我收到不同对象的流,我想知道在反序列化它们之前知道对象类的最佳方式。
{A:{...},B:{B1:{...},B2:{...}},C:{...}}
在这个例子中,我想知道3个对象已经发送给我了:A.class,B.class和C. class
感谢
文档包含使用任意值进行反序列化的示例类或两次传递(集合中的第一次一般反序列化,然后是内容反序列化)。
这个例子看起来完全像你所需要的。你可以调整它来使用
JsonObject obj = parser.parse(json).getAsJsonObject();
得到 JsonObject
而不是数组以便您可以迭代所有属性(使用入口集)并反序列化根据名称( a = gson.fromJson(myjsonelement,A.class);
)通过简单地将名称映射到类。
I try to use gson library to deserialize a flow of objects sent to me. In all examples i've seen, when the method fromJson is called, we already know what type of object we expect to have.
In my case, I receive a flow of different objects and i'd like to know the best way to know the classes of objects before deserialize them.
{ A : {...}, B : { B1 : {...}, B2 : {...} }, C : {...} }
In this example, I'd like to have a way to know that 3 objects have been sent to me : A.class, B.class and C.class
Thanks
The documentation contains examples of deserializations using arbitrary classes or in two passes (first general deserialization in a collection, then content deserialization).
This exemple looks exactly like what you need. You could adapt it to use
JsonObject obj = parser.parse(json).getAsJsonObject();
to get a JsonObject
instead of an array so that you can iterate on all properties (using entrySet) and deserialize according to the names (a = gson.fromJson(myjsonelement, A.class);
) by simply mapping names to classes.
这篇关于GSON反序列化:如何知道对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!