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?

3
  • how does binary formatter help caching? Commented Nov 7, 2012 at 6: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. Commented Nov 7, 2012 at 6:39
  • 1
    That is a limitation with JSON.net [default JSON serialization library used in Web API]. See this - stackoverflow.com/questions/10143420/…. You can try using the latest version of JSON.NET or find some other way to caching things. Commented Nov 7, 2012 at 10:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! Works fine for JsonFormatter, but is there a more general way? I have clients requesting Json, JsonP and Xml.
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.
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!
In my case it returned the class default values, like nothing was being passed down. This solved it. Thks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.