Skip to content

Instantly share code, notes, and snippets.

@spetz
Created July 16, 2016 05:44
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 spetz/e1567775608e9dbd041137e59cd3be25 to your computer and use it in GitHub Desktop.
Save spetz/e1567775608e9dbd041137e59cd3be25 to your computer and use it in GitHub Desktop.
//Create contract resolver to handle the sensitive data, ignored properties etc.
public class CustomContractResolver : CamelCasePropertyNamesContractResolver
{
private static readonly string[] ExcludedProperties =
{
"email", "password", "currentpassword", "newpassword", "token", "key
};
private static readonly string[] IgnoredProperties =
{
"file", "stream"
};
public static readonly CustomContractResolver Instance = new CustomContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (IgnoredProperties.Contains(property.PropertyName.ToLowerInvariant()))
{
property.Ignored = true;
return property;
}
if (ExcludedProperties.Contains(property.PropertyName.ToLowerInvariant()))
{
return new JsonProperty
{
PropertyName = property.PropertyName,
ValueProvider = CustomValueProvider.Instance,
PropertyType = property.PropertyType,
Readable = property.Readable
};
}
return property;
}
}
//Create value provider to encrypt/decrypt the data
public class CustomValueProvider : IValueProvider
{
private const string DefaultValue = "*****";
internal static readonly CustomValueProvider Instance = new CustomValueProvider();
public void SetValue(object target, object value)
{
}
public object GetValue(object target) => DefaultValue;
}
//Initialize contract resolver
var settings = new JsonSerializerSettings
{
ContractResolver = new CustomContractResolver(),
};
//Use new settings to serialize/deserialize object
return JsonConvert.SerializeObject(value, settings);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment