c# - 空 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
解决方案
我试过你的代码并且工作得很好,可能你正在切换 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"]
}
推荐阅读
- scala - 如何在 spark Scala 的 foldLeft 中使用条件?
- sql - 如何在 Netezza 中用双引号将列括起来
- pyspark - .isin() 带有来自数据框的列
- docker - Docker - 无法通过脚本删除容器内的文件
- oracle - AWS RDS 分配的存储大小
- bash - 如何计算日志文件中两行之间的时间差?
- google-sheets - 用于计算电子表格中用 , 或 / 分隔的名称的公式
- visual-studio - 如何在 Visual Studio 2019 中为类库项目应用嵌套文件
- c++ - 如何初始化向量
? - django - gunicorn 服务文件中的 wsgi 目录无法识别