I have a poco class containing PersonalData, like this:
public class UserInfo
{
[PersonalData]
public string Name { get; set; }
[PersonalData]
public string Address { get; set; }
[PersonalData]
public DateTime Dob { get; set; }
public bool IsActive { get; set; }
}
I have many scenario's I serialize this object and what I'd like to do is mask the Pii data like this "****" during the serialization process - I'm serializing this to write to logs for example.
I've attempted to implement my own serializer with this code:
public class PersonalDataSerializer<T> : JsonConverter<T>
where T: new()
{
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert.HasPiiData();
}
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// read here...
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
// write here...
throw new NotImplementedException();
}
}
I'm not sure how to implement the write method without just carrying out normal serialization then trying to work out properties with the attribute and doing some sort of string manipulation.
What would make this easier is if the custom implementation was on each property instead of the whole object.
I use this method to identify properties on a type that have the PersonalData
attribute:
public static class TypeExtensions
{
public static bool HasPiiData(this Type type)
{
return type.GetProperties().Any(p => p.IsPiiData());
}
public static bool IsPiiData(this PropertyInfo prop)
{
foreach (var att in prop.CustomAttributes)
{
if (att.AttributeType == typeof(PersonalDataAttribute))
{
return true;
}
if (att.AttributeType.Name.Contains("PersonalData"))
{
return true;
}
}
return false;
}
}
Any advice on how to implement custom serialization based on an attribute would be much appreciated :-)