XSD.EXE + JSON.NET - How to deal with xxxSpecified generated members?

陌路散爱 提交于 2019-11-29 16:09:50

You can create your own contract resolver to filter out xxxSpecified properties:

public class SkipSpecifiedContractResolver : DefaultContractResolver
{
    // As of 7.0.1, Json.NET suggests using a static instance for "stateless" contract resolvers, for performance reasons.
    // http://www.newtonsoft.com/json/help/html/ContractResolver.htm
    // http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Serialization_DefaultContractResolver__ctor_1.htm
    // "Use the parameterless constructor and cache instances of the contract resolver within your application for optimal performance."
    static SkipSpecifiedContractResolver instance;

    static SkipSpecifiedContractResolver() { instance = new SkipSpecifiedContractResolver(); }

    public static SkipSpecifiedContractResolver Instance { get { return instance; } }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);
        ILookup<string, JsonProperty> lookup = null;
        foreach (var property in properties)
        {
            if (property.GetIsSpecified != null && property.SetIsSpecified != null)
            {
                var name = property.UnderlyingName + "Specified";
                lookup = lookup ?? properties.ToLookup(p => p.UnderlyingName);
                var specified = lookup[name]
                    // Possibly also check for [XmlIgnore] being applied.  While not shown in the question, xsd.exe will always
                    // apply [XmlIgnore] to xxxSpecified tracking properties.
                    //.Where(p => p.AttributeProvider.GetAttributes(typeof(System.Xml.Serialization.XmlIgnoreAttribute),true).Any())
                    .SingleOrDefault();
                if (specified != null)
                    specified.Ignored = true;
            }
        }
        return properties;
    }
}

Then use it like:

var settings = new JsonSerializerSettings { ContractResolver = SkipSpecifiedContractResolver.Instance };
var object = JsonConvert.DeserializeObject<Foo>(request, settings);

If you want to do this always, you can set the contract resolver in the global JsonConvert.DefaultSettings:

JsonConvert.DefaultSettings = (() =>
{
    return new JsonSerializerSettings { ContractResolver = SkipSpecifiedContractResolver.Instance };
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!