首页 > 解决方案 > 空 json 列表被视为 null

问题描述

我有一个空 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; }
   }
}

我发布以下 JSON:

{
  "StringListNull": null,
  "StringListEmpty": [],
  "StringListPopulated": ["one", "two"]
}

这会发生:

调试结果

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

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

我错过了一些微不足道的事情吗?如何使空值成为空列表,空列表成为空列表?

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

/K

标签: c#jsonasp.net-mvc

解决方案


我试过你的代码并且工作得很好,可能你正在切换 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();
    }
}

这是一个简单的控制台应用程序来测试你的逻辑。编辑:用您的输入 JSON 测试:

{
  "StringListNull": null,
  "StringListEmpty": [],
  "StringListPopulated": ["one", "two"]
}

推荐阅读