如何在使用Gson序列化时暴露类名 [英] how to expose class names when serializing with Gson

查看:101
本文介绍了如何在使用Gson序列化时暴露类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的场景非常复杂,但总结如下:

我想了解一个编译器的源代码 - 并且了解每个AST节点代表的是什么'生成不同程序的AST的JSON序列化,然后检查可视化的JSON输出。

它工作的很好,除了一个问题是,在Gson生成的JSON数据类名称isn'提到,所以它仍然没有多大帮助。有没有办法给Gson输出添加类名而不费力气? (不需要为每个AST节点添加一些方法)。 code.google.com/p/genson/rel =nofollow> Genson 将您的对象的类名添加到输出的json,只需要:

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

好的一点是,它使您能够反序列化回到那些具体的类型。
了解更多详情,请参阅 wiki


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

解决方案

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.

这篇关于如何在使用Gson序列化时暴露类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆