Home > Software engineering >  Why is my JSON serializer giving a 500 error when changing property from byte[] to List<byte[]>
Why is my JSON serializer giving a 500 error when changing property from byte[] to List<byte[]>

Time:01-23

I was uploading images using a pure JSON input and Base64 encoding the images.

The code worked fine when I used property of type byte[]

But when I want to support upload of multiple files in one go and changed the property to List<byte[]> then I get a 500 error as follows

System.Private.CoreLib: Unable to cast object of type 'System.Byte[]' to type 'System.Collections.Generic.List`1[System.Byte[]]'

I am assuming the problem is in my serializer method which looks as follows

public class Base64FileJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(string);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader?.Value == null) return Array.Empty<byte>();

            return Convert.FromBase64String(reader.Value as string);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new InvalidOperationException("Read only converter");
        }
    }
}

The serializer is applied on the input model as follows

 [ApiBodyParameter(
        IsOptional = true,
        Description = "List/array of BASE64 encoded image data for the item images"
        )]
        [JsonConverter(typeof(Base64FileJsonConverter))]
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public List<byte[]> ResellImageBase64Data { get; set; }

I just cannot figure out what is wrong here and how to fix it?

I tried iterating the array but I cant figure out the right way

 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader?.Value == null) return Array.Empty<byte>();

            var returnList = new List<byte[]>();

            foreach (var image in reader.ReadAsBytes())
            {
                var jongel = Convert.FromBase64String(image.ToString());

                returnList.Add(jongel);
            }

            return returnList;
        }

CodePudding user response:

Tou need to return List<byte[]> instead of byte[] in your converter. So you need to manually iterate over array in JsonReader.

You need something like

if (reader.TokenType == JsonToken.StartArray)
{
    while (reader.Read())
    {
        if (reader.TokenType == JsonToken.EndArray)
            break;
        list.Add((string)reader.Value);
    }
}
  • Related