Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Parse byte[] to json without converting to base64 string

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);

It returns the output as
Json string output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading