Serialize/deserialise a byte[] using NewtonSoft Json

13,824

The following test code works fine for me using 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
Share:
13,824
user2825546
Author by

user2825546

Updated on June 04, 2022

Comments

  • user2825546
    user2825546 almost 2 years

    I have a problem with Json. It serializes a byte array into a base64 encoded string, e.g.,

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

    but it ignores the base64 encoded string when deserialising the string. I get a byte array but it is just AAA etc. converted to a byte array. If doesn't decode the base64 encoded string.