ASP.NET Web API使用下划线进行序列化

Jon*_*ski 1 serialization json xml-serialization json.net asp.net-web-api

我在ApiController中有以下简单代码:

public Version Get()
{
  var version = new System.Version(1, 1, 0, 0);
  return version;
}
Run Code Online (Sandbox Code Playgroud)

这导致以下结果:

JSON

{"_Major":1,"_Minor":1,"_Build":0,"_Revision":0}
Run Code Online (Sandbox Code Playgroud)

XML

<Version xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/System">
  <_Build>0</_Build>
  <_Major>1</_Major>
  <_Minor>1</_Minor>
  <_Revision>0</_Revision>
</Version>
Run Code Online (Sandbox Code Playgroud)

请注意,酒店前面有一个_.仅查看所有这些属性的类定义VersionGetters,我怀疑它与序列化添加的原因有关_.我也试图在这里找到有关为什么会发生这种情况的信息,但所有这些都说明了这一点Read-only properties are serialized by default.

问题是下划线搞乱了客户端的反序列化并导致版本0.0.0.0.

这是一个CLR类,我无法覆盖,所以如何删除下划线以便在客户端上正确反序列化?

Jam*_*ing 6

默认情况下,Web API序列化具有[Serializable]属性(例如Version)的类型的字段.我不是它的忠实粉丝,这就是为什么Json.NET默认不这样做,但这就是Web API人员想要的.

这将阻止Web API在JSON中执行它:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new DefaultContractResolver();
Run Code Online (Sandbox Code Playgroud)