简体   繁体   中英

ASP.NET Web API and [Serializable] class

I have a class that is marked with [Serializable]. When i return it from the Web API the field names are all funky.

Normally the JSON returned is

[{"OrderId":797 ...

JSON returned when using [Serializable]

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

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?

You just need this one-liner to get Json.NET to ignore the [Serializable] semantics again:

((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.

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