0

My scenario is very complicated but here's a summary:

I'm trying to understand source of a compiler -- and to understand what each AST node represents, I'm generating JSON serializations of ASTs of different programs and later inspect the visualized JSON output.

It works great except one problem is that in Gson generated JSON data class names isn't mentioned, so it still doesn't help much. Is there a way to add class names to Gson output without much effort? (without adding some method to every AST node etc.)

sinan
  • 6,809
  • 6
  • 38
  • 67

3 Answers3

4

You can also use Genson to add class name of your objects to the outputed json, just do:

Genson genson = new Genson.Builder().setWithClassMetadata(true).create();
String json = genson.serialize(yourNode);

The nice thing is that it enables you to deserialize back to those concrete types. See the wiki for more details.

eugen
  • 5,856
  • 2
  • 29
  • 26
  • I try to use genson but it have problem while deseriailize with => public class InstanceData { private LinkedList stateList=new LinkedList(); } – Hlex May 07 '14 at 09:45
  • @Hlex indeed there is no default converter for LinkedLists, but one can easily implement one, anyway in next version there will be some additional converters (including this one). Have a look [this issue](https://code.google.com/p/genson/issues/detail?id=10&thanks=10&ts=1399468254) is just opened. – eugen May 07 '14 at 13:11
  • Unfortunately, I just discovered that Genson does not consider class metadata for Arrays: **"Class metadata and the overall metadata mechanism is available only for object types and not for arrays or literal values. Metadata must always be the first name/value pairs in JSON objects."** – gvasquez Aug 07 '17 at 16:49
1

Gson provides an option to custom serialize and descrialize an object, by implementing the interface JsonSerializer (for serializing) and JsonDeserializer (for descralizing) you can ignore some parts of the JSON string (say _class:com.example.SomeSourceClass).

This would also mean that a generic/regular Gson isntance will fail to read your JSON string.

This would be a specific solution to your problem.

Here is the Gson Userguide

Anantha Sharma
  • 9,920
  • 4
  • 33
  • 35
  • thanks for your answer. unfortunately modifying classes is not an option for me, because I have some huge amount of classes. – sinan Oct 02 '13 at 13:36
0

Check runtimeAdapter ,

 RuntimeTypeAdapter<Node> nodeAdapter = RuntimeTypeAdapter.create(Node.class,"type");
 nodeAdapter.registerSubtype(Begin.class,"Begin");
 nodeAdapter.registerSubtype(State.class,"State");
 gsonBuilder.registerTypeHierarchyAdapter(Class.class, new GsonClassAdapter())
            .registerTypeAdapter(Node.class,nodeAdapter )
            .enableComplexMapKeySerialization().setPrettyPrinting();
 gson = gsonBuilder.create();
Hlex
  • 833
  • 8
  • 16