Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Newtonsoft.Json serializes byte[] as base64 but sbyte[] not?

byte[] encoding in base64,sbyte[] does not.

byte[] bs = {100,101};
Newtonsoft.Json.JsonConvert.SerializeObject(bs);//"ZGU="

sbyte[] sbs = {100,101};
Newtonsoft.Json.JsonConvert.SerializeObject(sbs);//"[100,101]"
like image 977
newpost Avatar asked Mar 14 '19 01:03

newpost


People also ask

How do you serialize an array in JSON?

To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for. Json.NET will serialize the collection and all of the values it contains.

Is Newtonsoft deprecated?

Despite being deprecated by Microsoft in . NET Core 3.0, the wildly popular Newtonsoft. Json JSON serializer still rules the roost in the NuGet package manager system for . NET developers.

What does Jsonconvert DeserializeObject do?

DeserializeObject Method. Deserializes the JSON to a . NET object.

What is Jsonserializersettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json.


2 Answers

It's just the way JSON.Net works, and I would suspect most serialisers do the same. Check the documentation which explicitly says that byte[] is serialised as a base64 encoded string.

All other arrays are treated as you would expect, as simple JSON array types where the elements are serialised according to the rules for the array's type. Meaning that sbyte[] will be serialised as an array of integers.

like image 186
DavidG Avatar answered Nov 14 '22 22:11

DavidG


The serialization guide in the documentation for JSON.Net shows that there is no serialization rule for sbyte[] array. There is, however, an entry for sbyte. sbyte will be serialized as int.

byte[] arrays will be serialized to a base64 string since it is explicitly defined in the guide, and as a convenience.

Since there is no rule for sbyte[] in the serialization guide the array will be treated like any other array, and it's members will be serialized according to the guide. Therefore, sbyte[] is serialised to int[] since sbyte serilaizes to int.

Please see image below:

enter image description here

like image 35
haldo Avatar answered Nov 14 '22 23:11

haldo