-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Weird behavior serializing byte array to JSON #89024
Comments
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis Issue DetailsSystem.Text.Json serialization behavior difference of primitive arrays. The exact same object but passed with a different static type will end up being serialized differently. I could understand this happening for polymorphic cases, but this case is just arrays of primitive types. Note that this is specific to a byte array as it serializes to Base64 if recognized as such, all other primitive arrays serialize as arrays of their elements. I don't think we can change/fix this, but I think it would be interesting to learn why and if this is intentional or not (and if we have tests for this difference). /cc @eerhardt
|
Per open-telemetry/opentelemetry-dotnet#4656 (comment) this is a side-effect of var data = new byte[] { 1 };
Console.WriteLine(JsonSerializer.Serialize(data)); // "AQ=="
Console.WriteLine(JsonSerializer.Serialize<IEnumerable<byte>>(data)); // [1]
Console.WriteLine(JsonSerializer.Serialize<Array>(data)); // [1] While we could decide that any type deriving from
This behavior is not specific to array types, STJ follows a decidedly type-directed approach when serializing values. For example the following is by design: var value = new Derived(1, 2);
Console.WriteLine(JsonSerializer.Serialize(value)); // {"y":2,"x":1}
Console.WriteLine(JsonSerializer.Serialize<Base>(value)); // {"x":1}
record Base(int x);
record Derived(int x, int y) : Base(x); |
Thanks for the explanation. I suspected we did this for the inheritance case (the Base/Derived), but it felt weird for array types. |
I wasn't around when the decision was made, but I suspect it was made to cater to requests to support Base64 encoded strings (and the relatively limited value of serializing a byte array as a JSON array of bytes). |
System.Text.Json serialization behavior difference of primitive arrays.
The exact same object but passed with a different static type will end up being serialized differently. I could understand this happening for polymorphic cases, but this case is just arrays of primitive types. Note that this is specific to a byte array as it serializes to Base64 if recognized as such, all other primitive arrays serialize as arrays of their elements.
I don't think we can change/fix this, but I think it would be interesting to learn why and if this is intentional or not (and if we have tests for this difference).
/cc @eerhardt
The text was updated successfully, but these errors were encountered: