Skip to content

Instantly share code, notes, and snippets.

@oakie
Created May 29, 2023 16:56
Show Gist options
  • Save oakie/2671b278a08d6cfa4ae421c488e31f4c to your computer and use it in GitHub Desktop.
Save oakie/2671b278a08d6cfa4ae421c488e31f4c to your computer and use it in GitHub Desktop.
Extension method which excludes any properties derived from the specified base class from being serialized into JSON.
private class ExampleA
{
public string PropertyA { get; set; } = "not wanted";
}
private class ExampleB : ExampleA
{
public string PropertyB { get; set; } = "wanted";
}
// ...
var options = new JsonSerializerOptions
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver()
.ExcludePropertiesFromType<ExampleA>()
};
var json = JsonSerializer.Serialize(new ExampleB(), options);
// Should produce JSON: {"PropertyB": "wanted"}
public static class JsonSerializerExtensions
{
public static DefaultJsonTypeInfoResolver ExcludePropertiesFromType<T>(this DefaultJsonTypeInfoResolver resolver)
{
return resolver.ExcludePropertiesFromType(typeof(T));
}
public static DefaultJsonTypeInfoResolver ExcludePropertiesFromType(this DefaultJsonTypeInfoResolver resolver, Type type)
{
if (resolver == null || type == null)
{
throw new ArgumentNullException();
}
var exclude = type.GetProperties().Select(x => x.Name).ToHashSet();
resolver.Modifiers.Add(typeinfo =>
{
if (typeinfo.Kind == JsonTypeInfoKind.Object && type.IsAssignableFrom(typeinfo.Type))
{
foreach (var property in typeinfo.Properties)
{
var name = property.GetMemberName();
if (name is not null && exclude.Contains(name))
{
property.ShouldSerialize = static (obj, value) => false;
}
}
}
});
return resolver;
}
public static string GetMemberName(this JsonPropertyInfo property) => (property.AttributeProvider as MemberInfo)?.Name;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment