.NET Core读取JSON反序列化遇空引用异常,求修复方案
JSON反序列化触发NullReferenceException的原因及修复方案
异常信息
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
该异常并非异步导致,核心原因是代码结构不符合System.Text.Json的序列化规则,导致反序列化失败后集合成员为null,遍历操作触发空引用异常。
核心问题与修复步骤
1. 公共字段无法被反序列化
System.Text.Json默认仅处理带get/set访问器的公共属性,而代码中所有成员均为公共字段(如public string controlable;),反序列化时无法为这些字段赋值,最终commands等集合成员保持默认的null值。
修复:将所有公共字段改为公共属性,添加get; set;访问器。
2. 内部结构体命名冲突+字段未使用属性
Item类中定义的内部结构体Object与系统类型System.Object重名,会造成解析歧义;同时结构体内部成员也为字段,同样无法被反序列化。
修复:
- 将内部结构体
Object重命名为LevelObject(或其他无冲突的名称); - 将结构体内部成员改为带
get; set;的公共属性。
3. 可选优化:添加序列化特性
可以给类和结构体添加[Serializable]特性,或给属性添加[JsonPropertyName]特性(当JSON键名与成员名不一致时),确保序列化规则匹配,提升代码健壮性。
修改后的完整代码
Item类
public class Item { public string Controlable { get; set; } public List<string> Commands { get; set; } public List<LevelObject> Objects { get; set; } public struct LevelObject { public string Symbol { get; set; } public ObjectPosition Position { get; set; } } public struct ObjectPosition { public int X { get; set; } public int Y { get; set; } } }
Program类(添加null判断避免异常)
public class Program { public static void Main(string[] args) { Item item = FileReader.Read<Item>("Levels/Level1.json"); // 增加null校验,防止空引用 if (item?.Commands != null) { foreach (string command in item.Commands) { Console.WriteLine(command); } } } }
FileReader类(无需修改,同步读取完全正常)
using System.Text.Json; using System.IO; public class FileReader { public static T Read<T>(string fileName) { string text = File.ReadAllText(fileName); return JsonSerializer.Deserialize<T>(text); } }
修改完成后,JSON内容可正常反序列化到Item对象中,遍历Commands时不会再触发空引用异常。
内容的提问来源于stack exchange,提问作者Muhammad Khalish Zhafran
相关产品推荐
相关产品推荐

