使用空合并运算符 ?? 配合 linq 的 toarray() 或 tolist(),可以将可能为 null 的 json 集合字段统一转换为非空的可用集合。具体做法是调用 jsonserializer.deserialize<list>>(json)</list> 获取值,若结果为 null 则通过 ?? new list<t>()</t> 提供默认空列表,从而避免后续遍历时的 nullreferenceexception。

JsonSerializer.Deserialize 遇到空输入会返回什么
JsonSerializer.Deserialize 在解析 JSON 数组时,如果 JSON 字符串为空(如 "")或值为 null,默认行为是返回 null 而不是空集合。这意味着直接对返回值进行 .Count 或 foreach 操作会抛出异常。为了安全处理,必须在反序列化后立即检查是否为 null,或者在反序列化前确保 JSON 格式正确。对于来自外部 API 的不确定数据,这种 null 返回是常态,因此必须显式处理。

using System;
using System.Collections.Generic;
using System.Text.Json;
public class Program
{
public static void Main()
{
string jsonWithNull = "{\"items\": null}";
string jsonWithEmptyArray = "{\"items\": []}";
string jsonWithMissing = "{}";
var data1 = JsonSerializer.Deserialize<Root>(jsonWithNull);
var data2 = JsonSerializer.Deserialize<Root>(jsonWithEmptyArray);
var data3 = JsonSerializer.Deserialize<Root>(jsonWithMissing);
Console.WriteLine($"Null Input: {data1.Items == null}");
Console.WriteLine($"Empty Array: {data2.Items.Count}");
Console.WriteLine($"Missing Key: {data3.Items == null}");
}
}
public class Root
{
public List<string> Items { get; set; }
}预期结果:Null Input: True, Empty Array: 0, Missing Key: True。这证实了当 JSON 中字段缺失或显式为 null 时,反序列化得到的集合属性为 null,而空数组则得到长度为 0 的列表。
exa-js 是 Exa 官方 JavaScript 软件开发工具包,Exa 是一个为 AI 工作流构建的网络搜索 API。它为代理提供了一种具体的方式来搜索网络、检索页面内容,并从代码中生成有来源的答案,而不是手动拼接原始 HTTP 调用。
如何安全地将可能为空的集合转为非空列表
最稳妥的方法是在获取反序列化结果后,立即应用空合并逻辑。可以使用 ?.ToArray() ?? new List<t>()</t> 模式,或者在类定义中使用自动属性的初始化器。推荐在业务逻辑入口处统一转换,这样后续代码无需重复判断。例如,将 List<t></t> 统一转为 IReadOnlyList<t></t> 或保持 List<t></t>,取决于是否需要修改集合内容。关键点是确保转换后的对象永远不是 null。

using System;
using System.Collections.Generic;
using System.Text.Json;
public class Program
{
public static void Main()
{
string json = "{\"items\": null}";
var root = JsonSerializer.Deserialize<Root>(json);
// 统一转换为非空可用集合
var safeItems = root.Items ?? new List<string>();
foreach (var item in safeItems)
{
Console.WriteLine(item);
}
Console.WriteLine("Safe iteration completed.");
}
}
public class Root
{
public List<string> Items { get; set; }
}预期结果:程序不会抛出异常,并输出 "Safe iteration completed."。这表明即使原始数据为 null,经过 ?? 处理后,safeItems 始终是一个有效的空列表实例,可以安全地进行遍历。
基于程序中某个输入、条件或结果的具体问题
当 JSON 数据中包含嵌套对象且其内部集合也为 null 时,上述方法同样适用。例如,如果 Root 类包含一个 Child 对象,而 Child 的 Tags 字段为 null,我们需要递归或逐层应用空合并逻辑。在实际开发中,建议封装一个通用的辅助方法,如 GetSafeList<t>(List<t> source)</t></t>,以简化代码。这样可以确保无论 JSON 结构多深,最终访问到的集合都是可用的,避免了大量的 if (list != null) 检查。

















