Student222 Student222 - 3 months ago 27
C# Question

Why does Json.Net not properly serialize byte[] when it is dictionary key?

I tried to serialize a

Dictionary<byte[] , int>
using Json.Net, however it convert all the byte[] as "System.Byte[]". But if I reverse the type of key and value in the Dictionary. It works very well using Base64 to serialize byte[]. I am wondering why it does not work for byte[] key? What's the reasoning behind?

Below is the code I tried:

var dict1 = new Dictionary<byte[], int>
[Guid.NewGuid().ToByteArray()] = 1,
[Guid.NewGuid().ToByteArray()] = 2
string dict1Json = JsonConvert.SerializeObject(dict1);
//{ "System.Byte[]":1,"System.Byte[]":2}

var dict2 = new Dictionary<int, byte[]>
[1] = Guid.NewGuid().ToByteArray(),
[2] = Guid.NewGuid().ToByteArray()
var dict2Json = JsonConvert.SerializeObject(dict2);
//{ "1":"JgrYtch/6Eq3Nyoe8pnnpg==","2":"KbfVMzjz20yCYvc9FiVKKA=="}


The author of Json.NET answered that on GitHub:

That's expected behavior. The key has to be a string. If Json.NET can't find any TypeConverter then it will call ToString.

Json.NET isn't finding a type converter, so it calls ToString on the key. ToString by default returns the name of the type, which in this case is "System.Byte[]".

Values of dictionaries have different behavior. The run through conversion logic, which is why they can be properly serialized as values since there is a BinaryConverter. Why this is is only known to the author, but I suspect it is performance related as well as a little-needed feature.

You are better off not using a collection as a key in your object model. If your keys are GUIDs, then just use System.Guid or convert the Guid to a string.