how to expose class names when serializing with Gson

旧时模样 提交于 2019-12-20 06:21:43

问题


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


回答1:


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.




回答2:


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




回答3:


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();


来源:https://stackoverflow.com/questions/19129711/how-to-expose-class-names-when-serializing-with-gson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!