Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting IgnoreSerializableAttribute Globally in Json.net

I'm working on a ASP.NET WebApi (Release Candidate) project where I'm consuming several DTOs that are marked with the [Serializable] attribute. These DTOs are outside of my control so I'm not able to modify them in any way. When I return any of these from a get method the resulting JSON contains a bunch of k__BackingFields like this:

<Name>k__BackingField=Bobby
<DateCreated>k__BackingField=2012-06-19T12:35:18.6762652-05:00

Based on the searching I've done this seems like a problem with JSON.NET's IgnoreSerializableAttribute setting and to resolve my issue I just need to set it globally as the article suggests. How do I change this setting globally in a ASP.NET Web api project?

like image 562
neonbytes Avatar asked Jun 20 '12 18:06

neonbytes


2 Answers

I found easy way to get rid of k__BackingField in the names.

This fragment should be somewhere in the Application_Start() in Global.asax.cs:

JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings;

Looks like the default setting takes care of it.

like image 76
VikVik Avatar answered Oct 05 '22 18:10

VikVik


Since the library does not expose a static setter for the DefaultContractResolver, I suggest you create a static wrapper over JsonConvert and it's Serialize*/Deserialize* methods (at least the ones you use).

In your static wrapper you can define a static contract resolver:

private static readonly DefaultContractResolver Resolver = new DefaultContractResolver
{
    IgnoreSerializableAttribute = true
};

This you can pass to each serialization method in the JsonSerializerSettings, inside your wrapper. Then you call your class throughout your project.

The alternative would be to get the JSON.NET source code and adjust it yourself to use that attribute by default.

like image 33
Marcel N. Avatar answered Oct 03 '22 18:10

Marcel N.