I'm writing a custom json converter that will serialize an object and mask certain fields that contains some sensitive information. I've created the converter, but when I'm serializing the object using my converter, I'm getting an empty string. Can someone tell me what I'm doing wrong?
public class Student
{
public string Name { get; set; }
public string Phone { get; set; }
}
class StudentJsonConverter : JsonConverter
{
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is Student student)
{
student.Phone = MaskString(student.Phone);
}
writer.WriteStartObject();
serializer.Serialize(writer, value);
writer.WriteEndObject();
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public override bool CanConvert(Type objectType) => typeof(Student) == objectType;
private static string MaskString(string sensitiveInformation) => string.IsNullOrWhiteSpace(sensitiveInformation) ? null : new string('*', sensitiveInformation.Length);
}
And here I'm using it:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new StudentJsonConverter());
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var student = new Student { Name = "name", Phone = "1234" };
var serializedString = JsonConvert.SerializeObject(student, settings);
Console.WriteLine(serializedString);
But I'm always getting an empty string.