I am attempting to serialize/deserialze an object using the System.Text.Json JsonSerializer. My container object is a "LicenseFile" which contains a "License" object along with a byte[] digital signature.
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; }
}
When serializing the LicenseFile, I would also like to first convert the License values to JSON and afterwards Base64. To do this, I created a custom JSON converter e.g.
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();
}
}
I would like to end up with a JSON output something like this:
{
"License": "BASE64_OF_LICENSE_OBJECT_JSON'D",
"Signature": "BASE64_OF_SIGNATURE_BYTE[]"
}
My questions:
- Is this a good approach? Would I better off to just use helper methods to serialize the values first, base64 them and then write them out to a file?
- How can I deserialze the JSON object back into objects again (while de-base64'ing them on the way)
Thanks for any recommendations!