简体   繁体   English

使用NewtonSoft Json序列化/反序列化一个字节[]

[英]Serialize/deserialise a byte[] using NewtonSoft Json

I have a problem with Json. 我对Json有问题。 It serializes a byte array into a base64 encoded string, eg, 它将字节数组序列化为base64编码的字符串,例如,

"UpdateSeq":{"$type":"System.Byte[], mscorlib","$value":"AAAAAAAJHxw="},

but it ignores the base64 encoded string when deserialising the string. 但在反序列化字符串时会忽略base64编码的字符串。 I get a byte array but it is just AAA etc. converted to a byte array. 我得到一个字节数组,但它只是AAA等。转换为字节数组。 If doesn't decode the base64 encoded string. 如果不解码base64编码的字符串。

The following test code works fine for me using Json.Net 6.0.4. 使用Json.Net 6.0.4,以下测试代码对我来说工作正常。

using System;
using System.Text;
using Newtonsoft.Json;

namespace JsonTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Testing";

            Foo foo = new Foo
            {
                UpdateSeq = Encoding.UTF8.GetBytes(str)
            };

            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Objects,
                Formatting = Formatting.Indented
            };

            string json = JsonConvert.SerializeObject(foo, settings);
            Console.WriteLine(json);

            Foo foo2 = JsonConvert.DeserializeObject<Foo>(json, settings);
            string str2 = Encoding.UTF8.GetString(foo2.UpdateSeq);
            Console.WriteLine();
            Console.WriteLine(str == str2 
                              ? "strings are equal" 
                              : "strings are NOT equal");
        }
    }

    public class Foo
    {
        public byte[] UpdateSeq { get; set; }
    }
}

Output: 输出:

{
  "$type": "JsonTest.Foo, JsonTest",
  "UpdateSeq": {
    "$type": "System.Byte[], mscorlib",
    "$value": "VGVzdGluZw=="
  }
}

strings are equal

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

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