https://stackoverflow.com/questions/56685266

CSharp · Console

/Program.cs

using System;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
					
public class Program
{
	public static void Main()
	{
		var foo = new Foo { Id = 123, Age = 23 };
		var settings = new JsonSerializerSettings
		{
			ContractResolver = new ExcludeObsoletePropertiesResolver()
		};
		var json = JsonConvert.SerializeObject(foo, settings);
		Console.WriteLine(json);
	}
}

public class ExcludeObsoletePropertiesResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty prop = base.CreateProperty(member, memberSerialization);
        if (prop.AttributeProvider.GetAttributes(true).OfType<ObsoleteAttribute>().Any())
        {
            prop.ShouldSerialize = obj => false;
        }
        return prop;
    }
}

public class Foo
{
    public int Id { get; set; }

    [Obsolete]
    public int Age { get; set; }
}
;