json object serialization/deserialization using google gson

后端 未结 2 634
渐次进展
渐次进展 2021-01-28 03:47

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,

2条回答
  •  面向向阳花
    2021-01-28 04:06

    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.

提交回复
热议问题