Skip to content

Instantly share code, notes, and snippets.

@sgissinger
Last active October 22, 2018 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgissinger/741d9fdd19ea8105196e5aa643399a65 to your computer and use it in GitHub Desktop.
Save sgissinger/741d9fdd19ea8105196e5aa643399a65 to your computer and use it in GitHub Desktop.
Json ContractResolver using custom attribute
public class CustomAttributeContractResolver<T> : DefaultContractResolver
where T : Attribute
{
private static List<string> typeOnePropertiesToSerialize = new List<string>();
private static List<string> typeTwoPropertiesToSerialize = new List<string>();
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization).ToList();
if (typeof(TypeOne).IsAssignableFrom(type))
{
if (!typeOnePropertiesToSerialize.Any())
FillPropertyList(typeOnePropertiesToSerialize, type);
properties.RemoveAll(x => !typeOnePropertiesToSerialize.Any(y => x.PropertyName == y));
}
else if (typeof(TypeTwo).IsAssignableFrom(type))
{
if (!typeTwoPropertiesToSerialize.Any())
FillPropertyList(typeTwoPropertiesToSerialize, type);
properties.RemoveAll(x => !typeTwoPropertiesToSerialize.Any(y => x.PropertyName == y));
}
return properties;
}
private void FillPropertyList(List<string> propertiesToSerialize, Type type)
{
var curProps = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var curProp in curProps)
{
var attr = curProp.GetCustomAttribute(typeof(T));
if (attr != null)
propertiesToSerialize.Add(curProp.Name);
}
}
}
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public class JsonSimulationAttribute : Attribute
{ }
public class MyController : ApiController
{
public HttpResponseMessage Simulate()
{
var results = new List<TypeOne>();
var json = new JsonMediaTypeFormatter
{
SerializerSettings = {
ContractResolver = new CustomAttributeContractResolver<JsonSimulationAttribute>()
}
};
return Request.CreateResponse(HttpStatusCode.OK, results, json);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment