如何从大型JSON载荷中反序列化特定子树并获取Time_off_type ID
解决System.Text.Json反序列化后对象为null的问题
以下是几个常见的排查方向和解决办法:
检查JSON结构与类定义的匹配度
网站自动生成的类很可能和实际JSON的层级结构不对应。比如你的JSON可能是外层嵌套了data这类节点,而你直接用Time_off_type去反序列化整个JSON字符串,导致反序列化器找不到匹配的结构,返回null。
举个例子,如果你的JSON是这种结构:{ "data": { "attributes": { "Id": 123 } } }那你需要先定义一个根类来匹配外层结构:
public class RootResponse { public Time_off_type data { get; set; } } public class Time_off_type { public Attributes attributes { get; set; } } public class Attributes { public int Id { get; set; } }然后反序列化到根类:
var root = System.Text.Json.JsonSerializer.Deserialize<RootResponse>(result); x.Id = root.data.attributes.Id;处理属性名称大小写或映射问题
System.Text.Json默认区分大小写,如果JSON里的键名(比如attributes写成Attributes、Id写成id)和类的属性名不一致,会导致属性无法绑定,最终对象为null。
解决办法有两种:- 开启忽略大小写的选项:
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var abwId = System.Text.Json.JsonSerializer.Deserialize<Time_off_type>(result, options); - 用
JsonPropertyName特性指定映射关系:public class Time_off_type { [JsonPropertyName("Attributes")] public Attributes attributes { get; set; } } public class Attributes { [JsonPropertyName("id")] public int Id { get; set; } }
- 开启忽略大小写的选项:
开启错误捕获定位问题
即使JSON格式合法,也可能存在其他隐性问题(比如不可见字符、属性类型不匹配)。可以通过捕获JsonException来获取具体错误信息:try { var abwId = System.Text.Json.JsonSerializer.Deserialize<Time_off_type>(result); x.Id = abwId.attributes.Id; } catch (JsonException ex) { // 打印异常信息,直接定位反序列化失败的原因 Console.WriteLine(ex.ToString()); }确认类的访问修饰符
确保Time_off_type类、attributes属性以及Id属性都是public修饰的,否则反序列化器无法访问这些成员,会返回null。
内容的提问来源于stack exchange,提问作者Steven Tumler
相关产品推荐
相关产品推荐

