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?

Malako
  • 534
  • 6
  • 20
  • how does binary formatter help caching? – DarthVader Nov 07 '12 at 06:04
  • 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. – Malako Nov 07 '12 at 06:39
  • 1
    That is a limitation with JSON.net [default JSON serialization library used in Web API]. See this - http://stackoverflow.com/questions/10143420/why-does-json-net-serialization-fail-with-serializable-and-a-lambda-inside-a-r. You can try using the latest version of JSON.NET or find some other way to caching things. – Suhas Nov 07 '12 at 10:03

1 Answers1

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.

Youssef Moussaoui
  • 12,187
  • 2
  • 41
  • 37
  • Thanks! Works fine for JsonFormatter, but is there a more general way? I have clients requesting Json, JsonP and Xml. – Malako Nov 08 '12 at 14:58
  • 1
    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. – Youssef Moussaoui Nov 08 '12 at 18:19
  • 1
    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! – Malako Nov 19 '12 at 22:38
  • In my case it returned the class default values, like nothing was being passed down. This solved it. Thks! – StinkyCat Jun 25 '14 at 19:04