NewtonSoft add JSONIGNORE at runTime

后端 未结 5 2249
一个人的身影
一个人的身影 2020-11-27 05:05

Am looking to Serialize a list using NewtonSoft JSON and i need to ignore one of the property while Serializing and i got the below code

pub         


        
5条回答
  •  孤城傲影
    2020-11-27 05:22

    I think it would be best to use a custom IContractResolver to achieve this:

    public class DynamicContractResolver : DefaultContractResolver
    {
        private readonly string _propertyNameToExclude;
    
        public DynamicContractResolver(string propertyNameToExclude)
        {
            _propertyNameToExclude = propertyNameToExclude;
        }
    
        protected override IList CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            IList properties = base.CreateProperties(type, memberSerialization);
    
            // only serializer properties that are not named after the specified property.
            properties =
                properties.Where(p => string.Compare(p.PropertyName, _propertyNameToExclude, true) != 0).ToList();
    
            return properties;
        }
    }
    

    The LINQ may not be correct, I haven't had a chance to test this. You can then use it as follows:

    string json = JsonConvert.SerializeObject(car, Formatting.Indented,
       new JsonSerializerSettings { ContractResolver = new DynamicContractResolver("LastModified") });
    

    Refer to the documentation for more information.

提交回复
热议问题