Json empty array deserializing as null in MVC Json empty array deserializing as null in MVC json json

Json empty array deserializing as null in MVC


ok, i was facing this issue almost 5 hours trying find the solution then i found myself looking in the MVC source code.and i found that this is a problem with the Mvc Source code in System.Web.Mvc.ValueProviderResultat Line 173:

        else if (valueAsArray != null)        {            // case 3: destination type is single element but source is array, so                     extract first element + convert            if (valueAsArray.Length > 0)            {                value = valueAsArray.GetValue(0);                return ConvertSimpleType(culture, value, destinationType);            }            else            {                // case 3(a): source is empty array, so can't perform conversion                return null;            }        }

as you can see if source is empty array it will return null.

so i have to find a way around it, and then i remember how in the good old days we was doing deserialization:this is how you will get what you want:

    public ActionResult ProcessCriteria(int id, Criteria criteria)    {        var ser = new System.Web.Script.Serialization.JavaScriptSerializer();        StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);        reader.BaseStream.Position = 0;        criteria = ser.Deserialize<Criteria>(reader.ReadToEnd());        return Json(_service.ProcessCriteria(id, criteria));    }


One way of resolving this issue is assigning a new instance as a default value for your ObjectsList like this:

public class Criteria{    public decimal? ANullableNumber { get; set; }    public IList<ObjectInList> ObjectsList { get; set; } = new List<ObjectInList>();}

This will create an empty List instead of null if there's no values in your JSON array.


I would think the actual problem is in DefaultModelBinder.cs line 711 where it returns null if the built objectList contains nothing. Check this out: https://lostechies.com/jimmybogard/2013/11/07/null-collectionsarrays-from-mvc-model-binding/