ASP.NET Web API 和 [Serializable] 类 [英] ASP.NET Web API and [Serializable] class
问题描述
我有一个用 [Serializable] 标记的类.当我从 Web API 返回它时,字段名称都很时髦.
I have a class that is marked with [Serializable]. When i return it from the Web API the field names are all funky.
通常返回的JSON是
[{"OrderId":797 ...
使用 [Serializable] 时返回的 JSON
JSON returned when using [Serializable]
[{"<OrderId>k__BackingField":797 ...
我不想将其标记为可序列化以使用 BinaryFormatter 进行缓存.除了编写自定义序列化程序或制作不可序列化的孪生类并编写猴子代码在两者之间转换"之外,还有其他方法吗?
I wan't to mark it serializable to use a BinaryFormatter for caching. 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?
推荐答案
你只需要这个单行代码就可以让 Json.NET 再次忽略 [Serializable] 语义:
You just need this one-liner to get Json.NET to ignore the [Serializable] semantics again:
((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;
对您来说更好的解决方案可能是完全摆脱 [Serializable],停止使用 BinaryFormatter,并使用不同的序列化程序来执行您想做的任何缓存,例如 Json.NET 序列化程序.
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.
这篇关于ASP.NET Web API 和 [Serializable] 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!