I have a problem with empty JSON lists deserializing to null while null values deserializes to an empty list.
Using this test scenario in a completely new MVC project:
public class TestController : Controller
{
public ActionResult Index(ImportObject importObject)
{
return Content("Response");
}
public class ImportObject
{
public List<string> StringListNull { get; set; }
public List<string> StringListEmpty { get; set; }
public List<string> StringListPopulated { get; set; }
}
}
I'm posting the following JSON:
{
"StringListNull": null,
"StringListEmpty": [],
"StringListPopulated": ["one", "two"]
}
And this happens:
The populated string list is expected. But in my mind the null value of StringListNull should result in it being null.
When passing the value [] I'm expecting it being turned into an empty list
Am I missing something trivial? How can I make the null value become a nulled list and the empty list become an empty list?
What controls the default serialization from JSON to the parameter class (ImportObject)?
/K
I tried your code and works absolutely fine, probably you are switching the StringListNull and StringListEmpty.
Here is how I tested it, try it out and see where you are making something wrong:
public class ImportObject
{
public List<string> StringListNull { get; set; }
public List<string> StringListEmpty { get; set; }
public List<string> StringListPopulated { get; set; }
}
class Program
{
static void Main(string[] args)
{
var sb = new StringBuilder();
var line = string.Empty;
while (!string.IsNullOrWhiteSpace((line = Console.ReadLine())))
{
sb.AppendLine(line);
}
var json = sb.ToString().Trim();
var inputObj = JsonConvert.DeserializeObject<ImportObject>(json);
Console.WriteLine();
}
}
This is a simple Console app to test your logic. Edit: tested with your input JSON:
{
"StringListNull": null,
"StringListEmpty": [],
"StringListPopulated": ["one", "two"]
}
Well, you can use Newtonsoft.Json or Json.NET for serializing or deserializing the Json. It will give you the required results.
This is the code I tried with it:
static void Convert()
{
string K = @"{ ""StringListNull"": null, ""StringListEmpty"": [], ""StringListPopulated"": [""one"", ""two""]}";
var list= JsonConvert.DeserializeObject<ImportObject>(K);
}
public class ImportObject
{
public List<string> StringListNull { get; set; }
public List<string> StringListEmpty { get; set; }
public List<string> StringListPopulated { get; set; }
}
And in the list object is exactly as you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With