https://stackoverflow.com/questions/51144399

CSharp · Console

/Program.cs

using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
					
public class Program
{
	public static void Main()
	{
		var settings = new JsonSerializerSettings
		{
			ContractResolver = new CustomResolver(),    // comment out this line to see what happens with [JsonObject(MemberSerialization.Fields)] applied but no resolver
			Formatting = Formatting.Indented
		};
		string json = JsonConvert.SerializeObject(new Foo(), settings);
		Console.WriteLine(json);
	}
}

[JsonObject(MemberSerialization.Fields)]    // comment out this line to see what the default serialization looks like with no customizations
class Foo
{
	private string privateField;
	public string publicField;
	internal string internalField;
	string defaultField;
	
	public string PublicProperty { get; set; }
	private string PrivateProperty { get; set; }
	public string GetOnlyProperty { get { return "blah"; } }
	
	public Foo()
	{
		privateField = "foo";
		publicField = "bar";
		internalField = "baz";
		defaultField = "quux";
		PublicProperty = "bang";
		PrivateProperty = "pow";
	}
}

class CustomResolver : DefaultContractResolver
{
	protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
	{
		JsonProperty prop = base.CreateProperty(member, memberSerialization);
		JsonObjectAttribute attr = prop.DeclaringType.GetCustomAttribute<JsonObjectAttribute>();
		if (attr != null && attr.MemberSerialization == MemberSerialization.Fields && 
			member.GetCustomAttribute<CompilerGeneratedAttribute>() != null)
		{
			prop.Ignored = true;
		}
		return prop;
	}
}
;