空的 json 列表被视为 null

Kir*_*ken 5 c# asp.net-mvc json

我在将空 JSON 列表反序列化为 null 而空值反序列化为空列表时遇到问题。

在一个全新的 MVC 项目中使用这个测试场景:

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; }
   }
}
Run Code Online (Sandbox Code Playgroud)

我发布以下 JSON:

{
  "StringListNull": null,
  "StringListEmpty": [],
  "StringListPopulated": ["one", "two"]
}
Run Code Online (Sandbox Code Playgroud)

这会发生:

调试结果

需要填充的字符串列表。但在我看来,StringListNull 的空值应该导致它为空。

当传递值 [] 我期待它变成一个空列表

我错过了一些微不足道的东西吗?如何使空值成为空列表而空列表成为空列表?

什么控制从 JSON 到参数类 (ImportObject) 的默认序列化?

/K

G.D*_*mov 1

我尝试了你的代码并且工作得很好,可能你正在切换 StringListNull 和 StringListEmpty。

在此输入图像描述

这是我测试的方法,你试试看,看看哪里出错了:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个简单的控制台应用程序,用于测试您的逻辑。编辑:使用您的输入 JSON 进行测试:

{
  "StringListNull": null,
  "StringListEmpty": [],
  "StringListPopulated": ["one", "two"]
}
Run Code Online (Sandbox Code Playgroud)