我遇到空 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"]
}
这发生了:
填充的字符串列表是预期的。但在我看来,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"]
}
关于c# - 空 json 列表被视为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56149327/