How to exclude property from Json Serialization
c#, json
Solution
EDIT 2023-06-29: updated answer and added info about .NET core and System.Text.Json
If you don't want to decorate properties with some attributes, or if you have no access to the class, or if you want to decide what to serialize during runtime, here's how you do it:
1. In Newtonsoft.Json
Newtonsoft solution is pretty simple:
//short helper class to ignore some properties from serialization
public class IgnorePropertiesResolver : DefaultContractResolver
{
private readonly HashSet<string> ignoreProps;
public IgnorePropertiesResolver(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;
}
}
Usage
JsonConvert.SerializeObject(YourObject, new JsonSerializerSettings()
{ ContractResolver = new IgnorePropertiesResolver(new[] { "Prop1", "Prop2" }) });
Make sure you cache the `ContractResolver` object if you decide to use this answer, otherwise performance may suffer.
I've published the code here in case anyone wants to add anything: https://github.com/jitbit/JsonIgnoreProps
2. In `System.Text.Json`
.NET core uses `System.Text.Json` by default, it's faster, but you don't have all the flexibility of Newtonsoft. However here some solutions for excluding properties at runtime:
In .NET 7 and above you can control which properties get serialized like described here: https://devblogs.microsoft.com/dotnet/system-text-json-in-dotnet-7/#example-conditional-serialization
In .NET 6 (and below) - you can cast to an interface (which I personally find the cleanest) or use a mapper. Both options are descibed in this answer https://stackoverflow.com/a/61344654/56621
Problem
I have a DTO class which I Serialize ``` Json.Serialize(MyClass) ``` How can I exclude a public property of it? (It has to be public, as I use it in my code somewhere else)