using Newtonsoft.Json.Serialization;
public static void Main()
alwaysExcluded = "shouldn't see this in JSON"
Console.WriteLine(SerializeForApiMethod(model, "method1"));
Console.WriteLine(SerializeForApiMethod(model, "method2"));
Console.WriteLine(SerializeForApiMethod(model, "method3"));
public static string SerializeForApiMethod(object model, string methodName)
Console.WriteLine($"--- {methodName} ---");
var settings = new JsonSerializerSettings
ContractResolver = new SelectivePropertyResolver(methodName),
Formatting = Formatting.Indented
return JsonConvert.SerializeObject(model, settings);
[UseWithApiMethods("method1", "method3")]
public int id { get; set; }
[UseWithApiMethods("method1")]
public string name { get; set; }
[UseWithApiMethods("method2")]
public int userId { get; set; }
[UseWithApiMethods("method2")]
public string color { get; set; }
public string alwaysExcluded { get; set; }
[AttributeUsage(AttributeTargets.Property)]
public class UseWithApiMethodsAttribute : Attribute
public UseWithApiMethodsAttribute(params string[] methodNames)
MethodNames = methodNames;
public string[] MethodNames { get; private set; }
public class SelectivePropertyResolver : DefaultContractResolver
public string ApiMethodName { get; private set; }
public SelectivePropertyResolver(string apiMethodName)
ApiMethodName = apiMethodName;
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
JsonProperty prop = base.CreateProperty(member, memberSerialization);
if (member.MemberType == MemberTypes.Property)
var att = ((PropertyInfo)member).GetCustomAttribute<UseWithApiMethodsAttribute>(true);
if (att == null || !att.MethodNames.Contains(ApiMethodName))