在序列化为 JSON 时,我尝试将选定的 string
值属性编码为 Base64,如以下问题所示:
Convert string property value to base64 on serialization
但我正在使用 System.Text.Json,因为随着 ASP.NET Core 3.0 的引入,默认的 JSON 序列化程序已从 Newtonsoft.Json 更改为 System.Text.Json。
怎么能 answer通过 Chris Richardson是否需要修改以与 System.Text.Json 一起使用?
最佳答案
创建以下custom JsonConverter<string>
:
public class Base64EncodedStringConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
Encoding.UTF8.GetString(reader.GetBytesFromBase64());
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) =>
writer.WriteBase64StringValue(Encoding.UTF8.GetBytes(value));
}
然后将其应用到您的模型,如下所示:
public class MyFoo
{
public string Value1 { get; set; }
[System.Text.Json.Serialization.JsonConverter(typeof(Base64EncodedStringConverter))] // Fully qualified attribute name used for clarity
public string Value2 { get; set; }
}
注释:
System.Text.Json
内置支持以 Base64 形式读写字节数组,因此不需要手动编码和解码 Base64。如果您不想允许空字符串值,请覆盖
JsonConverter<T>.HandleNull
返回true
并根据Read()
的要求抛出异常和Write()
(仅限 .NET 5 及更高版本)。
演示 fiddle here .
关于json - 在序列化时将字符串属性值转换为 base64 对于 ASP.NET Core 3.0+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67008507/