【问题标题】:"value can't be null" when adding JSON item to ListBox将 JSON 项添加到 ListBox 时“值不能为空”
【发布时间】:2014-08-28 20:22:58
【问题描述】:


我正在尝试从一个文件加载名称并将其添加到列表框中。
我要加载的代码:

if (File.Exists(file))
{
    List<Purchaser> Purchasers = JsonConvert.DeserializeObject<List<Purchaser>>(File.ReadAllText(file));
    Purchaser purchaser = new Purchaser();
    listDOF.Items.Add(purchaser.Name);
}

但这给了我一个例外,说该值不能为空。
在一个标签中应用名称值而不是像 label1.Text = purchaser.Name 这样的列表框进行测试,让标签为空!所以,我认为文件没有被加载或者我做错了什么。
对于 List 类,我有:

public class Purchaser
{
    public string Name { get; set; }
    public bool Paid { get; set; }
}
List<Purchaser> Purchasers = new List<Purchaser>();

文件按我想要的方式保存,但这不会将名称值加载到列表框。
有人可以帮帮我吗?我整天都在努力这样做!谢谢!

【问题讨论】:

  • 你在哪里使用反序列化对象Purchasers?你给listDOF.Items添加一个新初始化的对象是什么?
  • 我需要获取 Name 值并放入列表框中。为什么为空?我想从文件中读取它。不是这样吗?

标签: c# .net json winforms listbox


【解决方案1】:

new Purchaser().Name 始终为空1 因此Items.Add(null) throws an exception

要修复此错误,使用 JSON 信息 - 无需创建新的未初始化购买者。例如,

var json = File.ReadAllText(file);
var purchasers = JsonConvert.DeserializeObject<List<Purchaser>>(json);
// for each purchaser, add them to the list
for (var p in purchasers) {
  listDOF.Items.Add(p.Name ?? "{null}");
}

如上所述,ListBox.ObjectCollection.Add 不接受空值。虽然通过使用 JSON 中的信息解决了主要问题,但请注意额外使用 null-coalescing operator (??)。如果某人确实缺少名称(不要与空白名称混淆),使用此保护可防止异常 - 这不应该发生,但要防御!


1 Null 是引用类型的默认值,包括字符串;由于 (Name) 属性没有被分配任何其他值,它仍然是默认值 - 或 null。

【讨论】:

  • 好的,new Purchaser().Name 为空,但是这个listDOF.Items.Add(purchaser.Name); 会抛出异常吗?将 null 添加到 List 会引发异常吗?
  • @L.B 在WinForms ListBox, yes - 值不能为空。
  • @user2864740 现在我在从列表购买者中删除列表框中的选定购买者时遇到问题。在一个按钮的单击事件中,我有:if(listDOF.SelectedItems.Count != 0) { Purchaser purchaser = new Purchaser(); Purchasers.Remove(purchaser); listDOF.Items.Remove(listDOF.SelectedItem); } 但这不起作用。如何从列表购买者中删除 lisbox 中选择的实际购买者?
  • @Hypister 在确定具体问题问题并隔离一个小测试用例后提出不同的问题。
  • @Hypister 但是,请注意它源于相同的问题 - 使用 new Purchaser(),因此名称为 null。更新 Remove 以删除适当的项目(取决于点击按钮应该做什么)。
【解决方案2】:

试试这个。

if (File.Exists(file))
{
    var purchasers = JsonConvert.DeserializeObject<IEnumerable<Purchaser>>(File.ReadAllText(file));
    foreach(var purchaser in purchasers)
    {
        if(string.IsNullOrWhitespace(purchaser.Name))
        {
            //nulls are not allowed
            continue;
        }
        listDOF.Items.Add(purchaser.Name);
    }
}

当您这样做Purchaser purchaser = new Purchaser(); 时,您将创建一个新的单个实例,该实例除了默认值之外没有任何数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多