NewtonSoft add JSONIGNORE at runTime

后端 未结 5 2245
一个人的身影
一个人的身影 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:30

    Based on @Underscore post above, I created a list of properties to exclude on serialization.

    public class DynamicContractResolver : DefaultContractResolver {
        private readonly string[] props;
    
        public DynamicContractResolver(params string[] prop) {
            this.props = prop;
        }
    
        protected override IList CreateProperties(Type type, MemberSerialization memberSerialization) {
            IList retval = base.CreateProperties(type, memberSerialization);
    
            // retorna todas as propriedades que não estão na lista para ignorar
            retval = retval.Where(p => !this.props.Contains(p.PropertyName)).ToList();
    
            return retval;
        }
    }
    

    Use:

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

提交回复
热议问题