Reputation: 425
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?
Upvotes: 6
Views: 10338
Reputation: 22408
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);
Upvotes: 0
Reputation: 3127
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
Upvotes: 4