简体   繁体   English

如何编写可与.NET一起使用的Gson定制序列化适配器?

[英]How to write a custom serializer adapter for Gson that I can use with .NET?

I've got a .NET Rest webservice which delivers responses in Json. 我有一个.NET Rest网络服务,它在Json中提供响应。 I consume the webservice in Java. 我使用Java来使用Web服务。 I use Gson to serialize to and from Json. 我使用Gson来序列化Json。

I've got problems serializing between .NET and Java when it comes to polymorphism. 在涉及多态性时,我在.NET和Java之间进行序列化时遇到问题。

I've followed this guide in order to write a custom serializer adapter for Gson for my classes that extends an abstract class: http://www.javacodegeeks.com/2012/04/json-with-gson-and-abstract-classes.html 我已按照本指南进行操作,以便为我的类编写用于Gson的自定义序列化适配器,以扩展抽象类: http : //www.javacodegeeks.com/2012/04/json-with-gson-and-abstract-classes .html

The problem is that Gson then generates the following: 问题在于,Gson然后生成以下内容:

{"type":"Circle","properties":{"color":"red"}}

The default implementation in .NET does not understand the new "properties" attribute. .NET中的默认实现不了解新的“属性”属性。 What I need the adapter to write is the following: 我需要适配器编写的内容如下:

{"__type":"Circle","color":"red"}

How do I change the adapter to output this instead when serializing and who to deserialize it too? 如何在序列化时更改适配器以代替输出适配器,并且也要反序列化该适配器?

通过将以下内容添加到抽象基类中来解决该问题,以便Gson自动对其进行序列化:

private String __type = this.getClass().getSimpleName();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM