简体   繁体   中英

Serialize/Deserialize a byte array in JSON.NET

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!

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM