When dealing with JSON arrays that might be empty ([]) and you want them to deserialize correctly as empty collections instead of null, you can use attributes from Newtonsoft.Json, which is the default JSON serializer/deserializer used in ASP.NET MVC.
[JsonProperty] AttributeYou can use the [JsonProperty] attribute to specify default values for properties during deserialization. This can ensure that empty arrays are initialized correctly.
using Newtonsoft.Json; using System.Collections.Generic; public class YourModel { // Use JsonProperty to specify default value of an empty list [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] public List<string> Items { get; set; } } In this example, DefaultValueHandling.Populate ensures that when deserializing JSON, if the Items array is empty ([]), it will be initialized as an empty list (List<string>()) rather than null.
JsonSerializerSettingsYou can also configure JsonSerializerSettings globally or per request in your MVC application's configuration to handle empty arrays as desired.
// In Global.asax.cs or Startup.cs using Newtonsoft.Json; using System.Web.Http; protected void Application_Start() { // Configure JSON serialization settings GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include; } Alternatively, you can initialize your model properties in the constructor to ensure they are never null:
public class YourModel { public List<string> Items { get; set; } = new List<string>(); } This approach ensures that Items is always initialized as an empty list by default.
List<string>()).null if not initialized or configured otherwise.By using these approaches, you can ensure that JSON arrays, even when empty, deserialize correctly into non-null collections in your MVC application. Adjust the approach based on whether you need global configuration, attribute-level customization, or direct initialization of properties in your models.
C# JSON Deserialize Empty Array as Null
using Newtonsoft.Json; using System; public class MyClass { [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string[] MyArray { get; set; } } public class Program { public static void Main() { string json = "{\"MyArray\": []}"; MyClass obj = JsonConvert.DeserializeObject<MyClass>(json); Console.WriteLine(obj.MyArray == null ? "MyArray is null" : "MyArray is not null"); } } C# MVC Controller Action Handle Null or Empty Array
using Newtonsoft.Json; using System.Web.Mvc; public class MyModel { public string[] MyArray { get; set; } } public class MyController : Controller { [HttpPost] public ActionResult ProcessData(MyModel model) { if (model.MyArray == null) { // Handle null array } else if (model.MyArray.Length == 0) { // Handle empty array } else { // Process non-empty array } return View(); } } C# Deserialize JSON Empty Array to Default Value
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; public class MyConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(string[]); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JArray array = JArray.Load(reader); return array.Count == 0 ? new string[] { } : array.ToObject<string[]>(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } public class MyClass { [JsonConverter(typeof(MyConverter))] public string[] MyArray { get; set; } } public class Program { public static void Main() { string json = "{\"MyArray\": []}"; MyClass obj = JsonConvert.DeserializeObject<MyClass>(json); Console.WriteLine(obj.MyArray == null ? "MyArray is null" : "MyArray is not null"); } } C# MVC Handle Null or Empty Array in ModelState
using Newtonsoft.Json; using System.Web.Mvc; public class MyModel { public string[] MyArray { get; set; } } public class MyController : Controller { [HttpPost] public ActionResult ProcessData(MyModel model) { if (!ModelState.IsValid) { // Handle ModelState errors } if (model.MyArray == null) { ModelState.AddModelError("MyArray", "MyArray cannot be null."); } else if (model.MyArray.Length == 0) { ModelState.AddModelError("MyArray", "MyArray cannot be empty."); } else { // Process non-empty array } return View(); } } C# JsonPropertyAttribute NullValueHandling Example
JsonPropertyAttribute with NullValueHandling to handle empty arrays in JSON deserialization in C#.using Newtonsoft.Json; using System; public class MyClass { [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string[] MyArray { get; set; } } public class Program { public static void Main() { string json = "{\"MyArray\": []}"; MyClass obj = JsonConvert.DeserializeObject<MyClass>(json); Console.WriteLine(obj.MyArray == null ? "MyArray is null" : "MyArray is not null"); } } C# MVC Handle Empty JSON Array in Action Method
using Newtonsoft.Json; using System.Web.Mvc; public class MyModel { public string[] MyArray { get; set; } } public class MyController : Controller { [HttpPost] public ActionResult ProcessData(MyModel model) { if (model.MyArray == null) { ModelState.AddModelError("MyArray", "MyArray cannot be null."); } else if (model.MyArray.Length == 0) { ModelState.AddModelError("MyArray", "MyArray cannot be empty."); } else { // Process non-empty array } return View(); } } C# Deserialize JSON Null or Empty Array to Default Value
using Newtonsoft.Json; using System; public class MyClass { [JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)] public string[] MyArray { get; set; } } public class Program { public static void Main() { string json = "{\"MyArray\": []}"; MyClass obj = JsonConvert.DeserializeObject<MyClass>(json); Console.WriteLine(obj.MyArray == null ? "MyArray is null" : "MyArray is not null"); } } C# MVC Validate Empty JSON Array in Model Binding
using Newtonsoft.Json; using System.Web.Mvc; public class MyModel { public string[] MyArray { get; set; } } public class MyController : Controller { [HttpPost] public ActionResult ProcessData(MyModel model) { if (model.MyArray == null) { ModelState.AddModelError("MyArray", "MyArray cannot be null."); } else if (model.MyArray.Length == 0) { ModelState.AddModelError("MyArray", "MyArray cannot be empty."); } else { // Process non-empty array } return View(); } } C# Deserialize JSON Empty Array as Null with Custom Converter
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; public class MyConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(string[]); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JArray array = JArray.Load(reader); return array.Count == 0 ? null : array.ToObject<string[]>(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } public class MyClass { [JsonConverter(typeof(MyConverter))] public string[] MyArray { get; set; } } public class Program { public static void Main() { string json = "{\"MyArray\": []}"; MyClass obj = JsonConvert.DeserializeObject<MyClass>(json); Console.WriteLine(obj.MyArray == null ? "MyArray is null" : "MyArray is not null"); } } C# MVC Validate Null or Empty JSON Array
using Newtonsoft.Json; using System.Web.Mvc; public class MyModel { public string[] MyArray { get; set; } } public class MyController : Controller { [HttpPost] public ActionResult ProcessData(MyModel model) { if (model.MyArray == null) { ModelState.AddModelError("MyArray", "MyArray cannot be null."); } else if (model.MyArray.Length == 0) { ModelState.AddModelError("MyArray", "MyArray cannot be empty."); } else { // Process non-empty array } return View(); } } amazon-athena wampserver android-mediascanner inbox rstudio catplot poison-queue nested-class inner-classes gitlab-8