Skip to content

Instantly share code, notes, and snippets.

@NicoJuicy
Forked from pedroreys/Message.cs
Created September 9, 2021 11:11
Show Gist options
  • Save NicoJuicy/4dbd3e75deb630b002ab18153d11a891 to your computer and use it in GitHub Desktop.
Save NicoJuicy/4dbd3e75deb630b002ab18153d11a891 to your computer and use it in GitHub Desktop.
Defining a custom JsonConverter and using it with the built-in JsonConverterAttribute
public class Message
{
[JsonConverter(typeof(SHA256StringJsonConverter))]
public string Password { get; set; }
}
public class SHA256StringJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var hashedPassword = value.ToString().ToSHA256Hash();
writer.WriteValue(hashedPassword);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// The value should be hashed already. Nothing to do here.
return reader.Value;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment