Last active
October 22, 2018 22:31
-
-
Save sgissinger/741d9fdd19ea8105196e5aa643399a65 to your computer and use it in GitHub Desktop.
Json ContractResolver using custom attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] | |
public class JsonSimulationAttribute : Attribute | |
{ } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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