Skip to content

Instantly share code, notes, and snippets.

@arman-hpp
Created December 2, 2020 10:06
Show Gist options
  • Save arman-hpp/433c8483d8d1596bf5679321c1e908e8 to your computer and use it in GitHub Desktop.
Save arman-hpp/433c8483d8d1596bf5679321c1e908e8 to your computer and use it in GitHub Desktop.
JsonIgnore
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var person = new Person();
person.Code = "as";
person.Name = "asda";
var jsonResolver = new PropertyIgnoreSerializerContractResolver();
jsonResolver.IgnoreProperty(typeof(Person), "Code");
var json = JsonConvert.SerializeObject(person, new JsonSerializerSettings { ContractResolver = jsonResolver });
}
}
public class Person
{
public string Name { get; set; }
public string Code { get; set; }
}
public sealed class PropertyIgnoreSerializerContractResolver : DefaultContractResolver
{
private readonly Dictionary<Type, HashSet<string>> _ignores;
public PropertyIgnoreSerializerContractResolver()
{
_ignores = new Dictionary<Type, HashSet<string>>();
}
public void IgnoreProperty(Type type, params string[] jsonPropertyNames)
{
if (!_ignores.ContainsKey(type))
_ignores[type] = new HashSet<string>();
foreach (var prop in jsonPropertyNames)
_ignores[type].Add(prop);
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (IsIgnored(property.DeclaringType, property.PropertyName))
{
property.ShouldSerialize = i => false;
property.Ignored = true;
}
return property;
}
private bool IsIgnored(Type type, string jsonPropertyName)
{
if (!_ignores.ContainsKey(type))
return false;
return _ignores[type].Contains(jsonPropertyName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment