14

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?

neonbytes
  • 348
  • 2
  • 10

4 Answers4

37

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.

VikVik
  • 1,045
  • 2
  • 11
  • 15
2

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.

Marcel N.
  • 13,726
  • 5
  • 47
  • 72
0

For me, the following fixed the issue with circular references and k__BackingField.

In your WebApiConfig add the following to the Register() method:

JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings {

    ContractResolver = new DefaultContractResolver {
        IgnoreSerializableAttribute = true
    },
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings;
PhillyNJ
  • 3,859
  • 4
  • 38
  • 64
-2

Friends, don't declare properties like this:

public String DiscretionCode { get; set; } 

But, create auxiliar vars, like old....

private String discretionCode;

public String DiscretionCode 
{ 
    get { return discretionCode;}
    set { discretionCode = value; }
}