我正在编写一个自定义 json 转换器,它将序列化一个对象并屏蔽包含一些敏感信息的某些字段。我已经创建了转换器,但是当我使用转换器序列化对象时,我得到一个空字符串。有人能告诉我我做错了什么吗?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);}我在这里使用它: 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);但我总是得到一个空字符串。
1 回答
- 1 回答
- 0 关注
- 153 浏览
添加回答
举报
0/150
提交
取消