c# - 空 json 列表被视为 null

标签 c# json asp.net-mvc

我遇到空 JSON 列表反序列化为 null 而 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"]
}

这发生了:

Debugging result

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

当传递值 [] 时,我希望它变成一个空列表

我是否漏掉了一些微不足道的东西?如何使空值成为空列表,空列表成为空列表?

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

/K

最佳答案

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

enter image description here

我是这样测试的,试试看你哪里做错了:

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"]
}

关于c# - 空 json 列表被视为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56149327/

相关文章:

c# - 如何通过 HTTP 发送进程的标准输出

javascript - 如何从javascript函数向Action发送参数?

javascript - 使用 UTC 日期时间值初始化 moment.js

jquery - 如何从失败的 jQuery 请求中获取异常消息?

arrays - Swift 3 排序 jsonArray

javascript - jQuery 函数的范围

c# - ObservableCollection<> 与 List<>

c# - 为什么我在 C# 中会出现这些输出参数错误?

c# - 另一个消息框

javascript - JSON 内的数组收到空