【发布时间】:2021-07-29 01:32:30
【问题描述】:
我正在尝试使用 System.Text.Json JsonSerializer 序列化/反序列化对象。 我的容器对象是一个“LicenseFile”,其中包含一个“License”对象以及一个 byte[] 数字签名。
public class LicenseFile
{
public License License { get; set; }
public byte[] Signature { get; set; }
}
public class License
{
public string ProductName { get; set; }
public string ProductVersion { get; set; }
}
在序列化 LicenseFile 时,我还想先将 License 值转换为 JSON,然后再转换为 Base64。 为此,我创建了一个自定义 JSON 转换器,例如
public class LicenseFileConverter : JsonConverter<LicenseFile>
{
public override void Write(Utf8JsonWriter writer, LicenseFile licenseFile, JsonSerializerOptions options)
{
writer.WriteStartObject();
var json = JsonSerializer.Serialize(licenseFile.License);
byte[] jsonBytes = new UTF8Encoding().GetBytes(json);
writer.WriteBase64String("License", jsonBytes);
writer.WriteBase64String("Signature", licenseFile.Signature);
writer.WriteEndObject();
writer.Flush();
}
}
我希望得到类似这样的 JSON 输出:
{
"License": "BASE64_OF_LICENSE_OBJECT_JSON'D",
"Signature": "BASE64_OF_SIGNATURE_BYTE[]"
}
我的问题:
- 这是一个好方法吗?我最好只使用辅助方法先序列化值,base64 它们然后将它们写出到文件中?
- 如何将 JSON 对象反序列化回对象(同时在途中对它们进行 de-base64)
感谢您的任何建议!
【问题讨论】:
-
System.Text.Json.JsonSerializer已经将byte []数组序列化为 Base64 字符串,请参阅The JSON value could not be converted toSystem.Byte[]。但是为什么需要将License转换为Base64?它不像 Base64 编码实际上提供任何有意义的加密、混淆或奇偶校验。 -
我使用 Base64 只是为了防止偶然的可读性,而不是为了任何安全性。主要对如何在序列化请求和最终结果之间介入的一般技术感兴趣。
标签: c# base64 jsonserializer system.text.json