代码之家  ›  专栏  ›  技术社区  ›  Kevin Smith

无法将JSON值转换为System.Byte[]

  •  0
  • Kevin Smith  · 技术社区  · 5 年前

    在处理字节数组时,尝试反序列化以下JSON时出现以下异常,怎么了?

    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
    
    0 回复  |  直到 5 年前
        1
  •  7
  •   Joelius    5 年前

    Sytem.Text.Json 字节数组( byte[] )将序列化为base64字符串。他们说他们不会支持 字节[] 在数组中序列化为数字数组 github issue

    这里有一个自定义转换器,应该让你开始。也许你可以优化阅读一点,但这种方法所带来的性能冲击应该不会太坏。您可能想添加null和错误处理,但您已经明白了。

    JsonSerializerOptions . 请参阅 this docs page

    public class ByteArrayConverter : JsonConverter<byte[]>
    {
        public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            short[] sByteArray = JsonSerializer.Deserialize<short[]>(ref reader);
            byte[] value = new byte[sByteArray.Length];
            for (int i = 0; i < sByteArray.Length; i++)
            {
                value[i] = (byte)sByteArray[i];
            }
    
            return value;
        }
    
        public override void Write(Utf8JsonWriter writer, byte[] value, JsonSerializerOptions options)
        {
            writer.WriteStartArray();
    
            foreach (var val in value)
            {
                writer.WriteNumberValue(val);
            }
    
            writer.WriteEndArray();
        }
    }
    
    推荐文章