简体   繁体   English

在 JSON.NET 中序列化/反序列化字节数组

[英]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.但是当我用图像填充照片属性并通过 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?这听起来像是一个简单的问题,但我在网上看了几个小时后还没有找到解决方案,但是,如何在 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:您可以将 byte[] 转换为字符串,然后使用 JsonConvert 方法获取对象:

var bytesAsString = Encoding.UTF8.GetString(bytes);
var person = JsonConvert.DeserializeObject<Person>(bytesAsString);

If you are using LINQ to JSON , you can do this:如果您使用LINQ to JSON ,您可以这样做:

JObject.Parse(Encoding.UTF8.GetString(data));

The result will be a dynamic JObject .结果将是一个动态的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.虽然这可能并不完全是 OP 想要做的,但对于希望反序列化遇到此问题的byte[]其他人来说,它可能会派上用场。

Based on this answer, you could use the one below in net core:基于答案,您可以在 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>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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