Reputation: 521
I have a simple class with the following property:
[JsonObject(MemberSerialization.OptIn)]
public class Person
{
...
[JsonProperty(PropertyName = "Photograph"]
public byte[] Photograph { get; set; }
...
}
but this doesn't work when I populate the Photograph property with an image and transfer over http. This may sound like a simple question but I've yet to find a solution after looking online for hours, but, how do I serialise/deserialise a byte array in Json.NET? What attribute tags do I need, or, should I be doing this another way? Many thanks!
Upvotes: 50
Views: 152890
Reputation: 15335
Based on this answer, you could use the one below in net core:
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
namespace <MyNameSpace>
{
public static class ByteArrayExtensions
{
public static async Task<T> Deserialize<T>(this byte[] data) where T : class
{
using (var stream = new MemoryStream(data))
{
return await JsonSerializer.DeserializeAsync(stream, typeof(T)) as T;
}
}
}
}
Which may be considered to have the edge on readability:
var deserialized = await mySerializedByteArray.Deserialize<MyObjectClass>();
Upvotes: 1
Reputation: 36423
You can convert the byte[] into a string then use the JsonConvert method to get the object:
var bytesAsString = Encoding.UTF8.GetString(bytes);
var person = JsonConvert.DeserializeObject<Person>(bytesAsString);
Upvotes: 32
Reputation: 19630
public static T Deserialize<T>(byte[] data) where T : class
{
using (var stream = new MemoryStream(data))
using (var reader = new StreamReader(stream, Encoding.UTF8))
return JsonSerializer.Create().Deserialize(reader, typeof(T)) as T;
}
Upvotes: 40
Reputation: 18135
If you are using LINQ to JSON, you can do this:
JObject.Parse(Encoding.UTF8.GetString(data));
The result will be a dynamic JObject
.
While this might not be exactly what the OP was looking to do, it might come in handy for others looking to deserialize a byte[]
that come across this question.
Upvotes: 8