I want to convert my model to json, and it has a byte[] array that gets converted to a base64 string while converting to json. I’m not wanting to converting the byte[] array to string format.
Here is what I have tried
MyModel myObject = new MyModel
{
Id = 1,
Data = new byte[] { 0x01, 0x02, 0x03 }
};
string json = JsonSerializer.Serialize(myObject, options);
I want output as {"Id":[1],"Data":[1,2,3]}.
Edit:
I have code for above in powershell script which do the same
$CertificateJsonString = ConvertTo-Json $CertificateVaultObject -Compress
$CertificateSecureString = ConvertTo-SecureString -String $CertificateJsonString -AsPlainText –Force
>Solution :
System.Text.Json (and Json.NET) only serializes byte arrays as Base64, so if you declare your Data as some other collection or enumerable of bytes (but not object) it will be serialized as a JSON array, e.g:
public class MyModel
{
public int Id { get; set; }
public IEnumerable<byte>? Data { get; set; }
}
When serialized via:
MyModel myObject = new MyModel
{
Id = 1,
Data = new byte[] { 0x01, 0x02, 0x03 }
};
string json = JsonSerializer.Serialize(myObject, options);
Results in:
{"Id":1,"Data":[1,2,3]}
Demo fiddle #1 here.
Or, if you can’t change your model, you could introduce a JsonConverter<byte> that round-trips byte [] values as an array:
public class ByteConverter : JsonConverter<byte []>
{
public override void Write(Utf8JsonWriter writer, byte [] value, JsonSerializerOptions options) =>
JsonSerializer.Serialize(writer, value.AsEnumerable());
public override byte []? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch
{
JsonTokenType.String => reader.GetBytesFromBase64(),
JsonTokenType.StartArray => JsonSerializer.Deserialize<List<byte>>(ref reader)!.ToArray(),
JsonTokenType.Null => null,
_ => throw new JsonException(),
};
}
And serialize like so:
MyModel myObject = new MyModel
{
Id = 1,
Data = new byte[] { 0x01, 0x02, 0x03 }
};
var options = new JsonSerializerOptions { Converters = { new ByteConverter() } };
string json = JsonSerializer.Serialize(myObject, options);
And get the same result.
Demo fiddle #2 here.
Notes:
- As Panagiotis Kanavos notes in comments, using Base64-encoded strings for binary data is recommended by RFC 7493: The I-JSON Message Format. It is also widely supported by serializers including e.g. System.Text.Json, Json.NET and Java’s Jackson
ObjectMapper. The Base64 representation will also be more compact, so you might consider using it as-is.
