System.Text.Json反序列化带对象数组的对象时属性值为null/0如何解决
问题原因
- 核心原因为类定义与JSON结构不匹配:你定义的
SystemSettings中Devices属性为DeviceSettings类型数组,但实际JSON中Devices数组的每个元素是外层再包裹了一层DeviceSettings属性的对象,反序列化时无法找到对应映射关系,只能返回各类型的默认值(引用类型为null、值类型为0)。 - 次要排查项:System.Text.Json默认严格匹配属性名大小写,若实际JSON属性名与类属性大小写不一致也会触发映射失败,你提供的示例中二者大小写一致,不属于本次问题诱因。
解决方案
方案1:调整代码匹配现有JSON结构
新增一个数组元素包装类,对应JSON中Devices数组的外层结构:
public class DeviceItem { public DeviceSettings DeviceSettings { get; set; } }
修改SystemSettings的Devices属性类型:
public class SystemSettings { public string SystemType { get; set; } public DeviceItem[] Devices { get; set; } }
调整后即可正常反序列化,可通过systemSettings.Devices[0].DeviceSettings获取对应的设备配置。
方案2:调整JSON结构匹配现有代码
如果不想修改类定义,可删除JSON中Devices数组内多余的DeviceSettings包裹层:
{ "SystemType": "SingleDevice", "Devices": [ { "DeviceType": "Blah", "Generates": 4, "RAdd": 10, "TAdd": 10, "Distance": 1, "IpAddress": "192.168.0.21", "Port": 50002 } ]}
可选配置优化
如果后续存在属性名大小写不一致的场景,可在反序列化时添加忽略大小写的配置,避免映射失败:
var systemSettings = JsonSerializer.Deserialize<SystemSettings>(config, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

