开发者

json object serialization/deserialization using google gson

I want to serialize/deserialize java objects开发者_如何学Python to/from json. the google gson is preferable. Let I have class A:

class A {
  int x = 1;
  int y = 2; 
}

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.


Your second example isn't JSON. If you want something that maintains instance state and specific classes etc, check out YAML

http://www.yaml.org/


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.

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜