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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With