ASP.NET Web API and [Serializable] class
Asked Answered
J

1

15

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?

Jeraldinejeralee answered 7/11, 2012 at 6:1 Comment(3)
how does binary formatter help caching?Percyperdido
The orders are from an external system and it takes 10 seconds or so to get all orders from date zero via their API. It's much quicker to get the orders between last cached date and current date, store it in a cache and then return the complete list.Jeraldinejeralee
That is a limitation with JSON.net [default JSON serialization library used in Web API]. See this - #10143920. You can try using the latest version of JSON.NET or find some other way to caching things.Lamella
M
26

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.

Miguelmiguela answered 7/11, 2012 at 20:57 Comment(4)
Thanks! Works fine for JsonFormatter, but is there a more general way? I have clients requesting Json, JsonP and Xml.Jeraldinejeralee
No, there isn't. Every formatter is free to choose how to handle [Serializable] in its own way. The default XmlFormatter recognizes [Serializable], but you could switch to XmlSerializer to avoid that. 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.Miguelmiguela
I ended up using Json.NET serializer as you suggested. The performance is as good as BinaryFormatter and there is no need for the [Serializable] attribute. Put it in an answer and you'll get your cred. Thanks!Jeraldinejeralee
In my case it returned the class default values, like nothing was being passed down. This solved it. Thks!Trolley

© 2022 - 2024 — McMap. All rights reserved.