复杂对象中System.Collections.ObjectModel.Collection反序列化结果为空问题
System.Text.Json反序列化Collection属性为空的解决办法
核心原因
默认配置下,System.Text.Json 仅对公共可读写属性执行反序列化操作,你遇到的问题由以下两个常见原因导致:
- 示例中
ProductCategory类的Product成员定义为公共字段,而非属性,默认不参与反序列化 Collection类型属性未初始化,或属性无写入权限,序列化器无法为属性赋值或填充元素
解决方案
方案1(推荐):调整实体类定义为标准属性
将类成员改为公共属性,同时初始化集合属性,避免空引用:
public class ProductCategory { // 改为带get/set的公共属性 public string ProductCategoryName { get; set; } // 改为属性并初始化集合实例,序列化器可直接往已有集合中填充元素 public System.Collections.ObjectModel.Collection<Product> Product { get; set; } = new(); } // Product类同样需要定义公共属性和JSON键对应 public class Product { public string entry1 { get; set; } public string entry2 { get; set; } }
原有反序列化代码无需修改即可正常运行。
方案2:开启公共字段支持
如果需要保留字段定义,可在序列化配置中开启IncludeFields参数:
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, // 开启公共字段的序列化/反序列化支持 IncludeFields = true }; var result = JsonSerializer.Deserialize<ProductCategory>(productCategoryString, options);
注:
IncludeFields参数从.NET 5版本开始支持,.NET Core 3.1及更低版本需要使用方案1调整实体类定义。
内容的提问来源于stack exchange,提问作者briswill
相关产品推荐
相关产品推荐

