如何写一个自定义的串行适配器GSON,我可以用.NET中使用?可以用、串行、自定义、适配器

2023-09-04 01:24:06 作者:磕磕绊绊绝不言分离

我已经有了一个.NET Web服务休息而以JSON提供响应。我消耗在Java的web服务。我用GSON序列化和从JSON。

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.

我有.NET和Java之间序列化,当涉及到多态的问题。

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

我已经照着为了写一个自定义的串行适配器GSON我的类继承抽象类本指南: http://www.java codegeeks.com / 2012/04 / JSON-与-GSON和 - 抽象classes.html

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然后生成以下内容:

The problem is that Gson then generates the following:

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

在.NET中的默认实现不理解新的属性属性。我需要写的适配器如下:

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系列化解决了:

Solved it by adding the following to the abstract base class so it's automatically serialized by Gson:

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