0

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.

Donato Szilagyi
  • 4,279
  • 4
  • 36
  • 53
Boris
  • 1
  • 2

2 Answers2

0

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/

Falmarri
  • 47,727
  • 41
  • 151
  • 191
  • I only need add one field per object which will describe a class name. JSON is native for android, so i prefer use it. – Boris Dec 25 '10 at 01:39
  • It will solve "serialization" side, but deseriaization remain problematic. – Boris Dec 25 '10 at 11:09
  • Yeah, I don't think json is equipped to do what you want. You should really check out yaml. YAML is a superset of JSON and it can do pretty much exactly what you want (assuming I understand what you want) – Falmarri Dec 25 '10 at 19:17
0

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.

Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97