简体   繁体   English

ASP.NET Web API和[Serializable]类

[英]ASP.NET Web API and [Serializable] class

I have a class that is marked with [Serializable]. 我有一个标有[Serializable]的类。 When i return it from the Web API the field names are all funky. 当我从Web API返回它时,字段名称都很时髦。

Normally the JSON returned is 通常返回的JSON是

[{"OrderId":797 ...

JSON returned when using [Serializable] 使用[Serializable]时返回JSON

[{"<OrderId>k__BackingField":797 ...

I wan't to mark it serializable to use a BinaryFormatter for caching. 我不想将其标记为可序列化以使用BinaryFormatter进行缓存。 Is there any other way than to write a custom serializer or to make a twin class that is not serializable and write monkey code to "cast" between the two? 除了编写自定义序列化程序或制作一个不可序列化的双胞胎并编写猴子代码以在两者之间“施放”之外,还有其他方法吗?

You just need this one-liner to get Json.NET to ignore the [Serializable] semantics again: 你只需要这个单行来让Json.NET再次忽略[Serializable]语义:

((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;

A better solution for you might be to get rid of [Serializable] altogether, stop using BinaryFormatter, and use a different serializer instead to do whatever caching you want to do, like the Json.NET serializer for example. 一个更好的解决方案可能是完全摆脱[Serializable],停止使用BinaryFormatter,并使用不同的序列化程序来做你想要做的任何缓存,例如Json.NET序列化程序。

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

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