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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9337255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:58:02  来源:igfitidea点击:

Serialize/Deserialize a byte array in JSON.NET

c#jsonserializationjson.net

提问by Steve Randall

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!

但是当我用图像填充照片属性并通过 http 传输时,这不起作用。这听起来像是一个简单的问题,但我在网上看了几个小时后还没有找到解决方案,但是,如何在 Json.NET 中序列化/反序列化字节数组?我需要什么属性标签,或者,我应该以另一种方式这样做吗?非常感谢!

回答by Oliver

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

回答by Alexey Zimarev

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

回答by dana

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[]遇到这个问题的其他人来说,它可能会派上用场。