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,
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.