I'm getting the following exception when trying to deserialize the following JSON when dealing with byte arrays, what's wrong?
public class Program
{
public static void Main()
{
var root = JsonSerializer.Deserialize<JsonRoot>(@"{ ""ByteArray"": [1] } ");
}
public class JsonRoot
{
public byte[] ByteArray {get;set;}
}
}
Unhandled exception. System.Text.Json.JsonException: The JSON value could not be converted to System.Byte[]. Path: $.ByteArray | LineNumber: 0 | BytePositionInLine: 16.
---> System.InvalidOperationException: Cannot get the value of a token type 'StartArray' as a string.
at System.Text.Json.Utf8JsonReader.TryGetBytesFromBase64(Byte[]& value)
at System.Text.Json.Utf8JsonReader.GetBytesFromBase64()
at System.Text.Json.Serialization.Converters.JsonConverterByteArray.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
at System.Text.Json.JsonPropertyInfoNotNullable`4.OnRead(ReadStack& state, Utf8JsonReader& reader)
at System.Text.Json.JsonPropertyInfo.Read(JsonTokenType tokenType, ReadStack& state, Utf8JsonReader& reader)
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
--- End of inner exception stack trace ---
at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& readStack, Utf8JsonReader& reader, Exception ex)
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
at System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
at Program.Main()
Command terminated by signal 6
int[]
. This is probably a limitation or bug in the serializer. Have you searched the github repo? – VitriformJsonRoot
objectvar test = new JsonRoot { ByteArray = new[] { (byte)1 } };
and serialize it for the test, and got{"ByteArray":"AQ=="}
result. It seems, that under the hoodSystem.Text.Json
uses special rules for byte arrays. Maybe because it's usingUtf8JsonReader
/Utf8JsonWriter
– Petrosal