<PackageReference Include="NJsonSchema" Version="11.3.2" />

PropertyRenameAndIgnoreSerializerContractResolver

JsonConvert resolver that allows to ignore and rename properties for given types.
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; namespace NJsonSchema.Infrastructure { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] public class PropertyRenameAndIgnoreSerializerContractResolver : DefaultContractResolver { private readonly Dictionary<string, HashSet<string>> _ignores; private readonly Dictionary<string, Dictionary<string, string>> _renames; public PropertyRenameAndIgnoreSerializerContractResolver() { _ignores = new Dictionary<string, HashSet<string>>(); _renames = new Dictionary<string, Dictionary<string, string>>(); } public void IgnoreProperty(Type type, params string[] jsonPropertyNames) { if (!_ignores.TryGetValue(type.FullName, out HashSet<string> value)) { value = new HashSet<string>(); _ignores[type.FullName] = value; } foreach (string item in jsonPropertyNames) { value.Add(item); } } public void RenameProperty(Type type, string propertyName, string newJsonPropertyName) { if (!_renames.TryGetValue(type.FullName, out Dictionary<string, string> value)) { value = new Dictionary<string, string>(); _renames[type.FullName] = value; } value[propertyName] = newJsonPropertyName; } protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { JsonProperty jsonProperty = base.CreateProperty(member, memberSerialization); if (jsonProperty.DeclaringType != (Type)null && jsonProperty.PropertyName != null && IsIgnored(jsonProperty.DeclaringType, jsonProperty.PropertyName)) { jsonProperty.Ignored = true; jsonProperty.ShouldSerialize = ((object i) => false); jsonProperty.ShouldDeserialize = ((object i) => false); } if (jsonProperty.DeclaringType != (Type)null && jsonProperty.PropertyName != null && IsRenamed(jsonProperty.DeclaringType, jsonProperty.PropertyName, out string newJsonPropertyName)) jsonProperty.PropertyName = newJsonPropertyName; return jsonProperty; } private bool IsIgnored(Type type, string jsonPropertyName) { if (!_ignores.TryGetValue(type.FullName, out HashSet<string> value)) return false; return value.Contains(jsonPropertyName); } private bool IsRenamed(Type type, string jsonPropertyName, [System.Runtime.CompilerServices.Nullable(2)] out string newJsonPropertyName) { if (!_renames.TryGetValue(type.FullName, out Dictionary<string, string> value) || !value.TryGetValue(jsonPropertyName, out newJsonPropertyName)) { newJsonPropertyName = null; return false; } return true; } } }