简体   繁体   中英

json object serialization/deserialization using google gson

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; 
}

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;} 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM