Serialize .Net object to json, controlled using xml attributes

后端 未结 4 1417
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 00:27

I have a .Net object which I\'ve been serializing to Xml and is decorated with Xml attributes. I would now like to serialize the same object to Json, preferably using the N

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 01:18

    You could create a custom contract resolver which would allow you to make adjustments to the properties and set them to ignore where an XmlIgnoreAttribute is set.

    public class CustomContractResolver : DefaultContractResolver
    {
        private readonly JsonMediaTypeFormatter formatter;
    
        public CustomContractResolver(JsonMediaTypeFormatter formatter)
        {
            this.formatter = formatter;
        }
    
        public JsonMediaTypeFormatter Formatter
        {
            [DebuggerStepThrough]
            get { return this.formatter; }
        }
    
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);
            this.ConfigureProperty(member, property);
            return property;
        }
    
        private void ConfigureProperty(MemberInfo member, JsonProperty property)
        {
            if (Attribute.IsDefined(member, typeof(XmlIgnoreAttribute), true))
            {
                property.Ignored = true;
            }            
        }
    }
    

    You can use apply this custom resolver by setting the ContractResolver property of the JsonSerializerSettings when serializing an object

    https://www.newtonsoft.com/json/help/html/ContractResolver.htm

    string json =
        JsonConvert.SerializeObject(
            product, // this is your object that has xml attributes on it that you want ignored
            Formatting.Indented,
            new JsonSerializerSettings { ContractResolver = new CustomResolver() }
            );
    

    If you're using WebApi you can set it globally to apply to all contracts.

    var config = GlobalConfiguration.Configuration;
    var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
    jsonSettings.ContractResolver = new CustomContractResolver();
    

提交回复
热议问题