JsonSerializer Deserialize byte array

8.5k views Asked by At

When deserialising byte array using Newtonsoft we can achieve by writing the following code

 var stringValue = Encoding.UTF8.GetString(byteArray);
 T data = JsonConvert.DeserializeObject<T>(stringValue);

But how do you do the equivalent using System.Text.Json? knowing that it is encoding UTF8?

2

There are 2 answers

3
HMZ On

This is a working example of how to deserialize with a byte array of a UTF8 string (using System.Text.Json):

class Program
{
    static void Main(string[] args)
    {

        try
        {
            string str = "{ \"MyProperty1\":\"asd\",\"MyProperty2\":2 }";
            byte[] utfBytes = Encoding.UTF8.GetBytes(str);
            var jsonUtfReader = new Utf8JsonReader(utfBytes);
            ModelDTO modelDTO = JsonSerializer.Deserialize<ModelDTO>(ref jsonUtfReader);
            Console.WriteLine($"First:{modelDTO.MyProperty1}, Second:{modelDTO.MyProperty2}");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

ModelDTO

public class ModelDTO
{
    public string MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }      
}

Output:

First:asd, Second:2

0
Mohammad Dayyan On

Serialize Byte Array to JSON:

var bytes = MyByteArray;
var jsonString = JsonConvert.SerializeObject(bytes.Select(item => (int)item).ToArray());
// jsonString = [1, 0, 1, 0, 0, 0]

Deserialize JSON to ByteArray:

// jsonString = [1, 0, 1, 0, 0, 0]
var bytesArray = JsonConvert.DeserializeObject<byte[]>(jsonString);