Setting IgnoreSerializableAttribute Globally in Json.net

人盡茶涼 提交于 2019-12-28 14:41:08

问题


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?


回答1:


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.




回答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.




回答3:


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;



回答4:


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; }
}


来源:https://stackoverflow.com/questions/11125476/setting-ignoreserializableattribute-globally-in-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!