Newtonsoft Json ignore property dynamically during serialization

edx
edx
90 Points
30 Posts

I want to ignore some properties for logging purpose only i.e. want to ignore these during run time json serialization:

Foo foo = new Foo
{
    Id = 1,
    Name = "Thing 1",
    DetailName = null,  
};

string json = JsonConvert.SerializeObject(foo); // Want to ignore DetailName
Views: 141
Total Answered: 2
Total Marked As Answer: 2
Posted On: 25-Feb-2021 04:01

Share:   fb twitter linkedin
Answers
Priya
Priya
Member
132 Points
36 Posts
         

You can do by custom contact resolver. You can extend DefaultContractResolver as follow:

public class JsonIgnoreResolver : DefaultContractResolver
    {
        private readonly HashSet<string> ignoreProps;
        public JsonIgnoreContractResolver(IEnumerable<string> propNamesToIgnore)
        {
            this.ignoreProps = new HashSet<string>(propNamesToIgnore);
        }

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);
            if (this.ignoreProps.Contains(property.PropertyName))
            {
                property.ShouldSerialize = _ => false;
            }
            return property;
        }
    }

 

And we can use like as:

string json = JsonConvert.SerializeObject(foo, new JsonSerializerSettings { ContractResolver = new JsonIgnoreResolver("DetailName") });
Posted On: 07-Mar-2021 02:41
Rahul Maurya
Rahul M...
Moderator
1264 Points
222 Posts
         

NewtonSoft JSON has a built-in feature to ignore property serialization on the basic on some condition dynamically. Something like:

public bool ShouldSerialize<PUT_YOUR_PROPERTY_NAME_HERE>()
{
    if(someCondition){
        return true;
    }else{
        return false;
    }
}

 

It's called "conditional property serialization" and the documentation mentioned here: https://www.newtonsoft.com/json/help/html/conditionalproperties.htm

In your case use as following:

public class Foo
{
    public int Id {get; set;}
    public string Name {get; set;}
    public string DetailName {get; set;}
    
    public bool ShouldSerializeDetailName()
    {        
        return false;
    }    
}

And then

string json = JsonConvert.SerializeObject(foo);
Posted On: 07-Mar-2021 02:58
 Log In to Chat