使用谷歌gson的json对象序列化/反序列化 [英] json object serialization/deserialization using google gson
问题描述
我想序列化/反序列化Java对象到/从json。谷歌GSON是可取的。
让我有A类:
I want to serialize/deserialize java objects to/from json. the google gson is preferable. Let I have class A:
class A {
int x = 1;
int y = 2;
}
然后,如果我调用新的Gson()。toJson(new A()),我会得到以下结果:
Then, if I call new Gson().toJson(new A()) I will get the following:
{ x: 1, y : 2}.
然而,我想要有
However I want to have
{class : "A", x:1, y:2}
所以我可以在不知道类名的情况下使用反射进行反序列化时间。我该怎么做?
谢谢。
So I can deserialize it using reflection without knowing the class name at compile time. How may I do it? Thank you.
推荐答案
如果使用Gson或更好,那么具体到如何生成JSON结构类的结构
,目前需要实现自定义序列化。同样,要从此JSON反序列化为此Java结构,则必须实现自定义反序列化。 {class:A,x:1,y:2}
class A {int x = 1; int y = 2;}
If Gson use is preferable or required, then specific to the question of how to generate JSON of the structure {class:"A", x:1, y:2}
from a Java instance of the structure class A {int x = 1; int y = 2;}
, it's currently necessary to implement custom serialization. Similarly, to deserialize from this JSON to this Java structure, then it's necessary to implement custom deserialization.
与此类手动处理不同,请注意,Gson很快将拥有 RuntimeTypeAdapter
可用于更简单的多态反序列化。请参阅 http://code.google.com/p/google- gson / issues / detail?id = 231 了解更多信息。即使您不能使用 RuntimeTypeAdapter
,它至少提供了一个创建可配置的自定义反序列化器的示例。
Instead of such "manual" processing, note that Gson will soon have the RuntimeTypeAdapter
available for simpler polymorphic deserialization. See http://code.google.com/p/google-gson/issues/detail?id=231 for more info. Even if you cannot use the RuntimeTypeAdapter
, it at least provides an example for creating a configurable custom deserializer.
如果您可以切换JSON映射API,然后我建议考虑 Jackson ,因为它具有可用的相对简单的多态解串器机制。我在 http://programmerbruce.blogspot上发布了一些简单的示例.com / 2011/05 / deserialize-json-with-jackson-into.html 。
If you can switch JSON mapping APIs, then I recommend considering Jackson, as it has a working and relatively simple polymorphic deserializer mechanism available. I posted some simple examples at http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html.
这篇关于使用谷歌gson的json对象序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!