简体   繁体   中英

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. I consume the webservice in Java. I use Gson to serialize to and from Json.

I've got problems serializing between .NET and Java when it comes to polymorphism.

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

The problem is that Gson then generates the following:

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

The default implementation in .NET does not understand the new "properties" attribute. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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