.NET 6中如何检测嵌套对象seqNum是否包含null值?
验证JSON反序列化后数组对象中无Null属性的实现方案
问题场景
在.NET 6环境下,通过以下代码将接口响应反序列化为JSON对象:
var responseBody = await response.Content.ReadAsStringAsync(); var deviceSeqNrResponse = JsonConvert.DeserializeObject(responseBody);
得到的对象结构如下:
{ "dataMod": 1, "deviceId": "myDeviceID", "seqNum": [ { "ApplicationType": null, "exampleId": 8 } ] }
需要编写测试断言,验证seqNum数组中的所有对象不存在值为null的属性,尝试过Contains方法但未成功。
可行解决方案
方案一:使用强类型模型(推荐)
首先定义对应JSON结构的强类型类,获得更好的类型安全和代码可读性:
public class DeviceSeqNrResponse { public int dataMod { get; set; } public string deviceId { get; set; } public List<SeqNumItem> seqNum { get; set; } } public class SeqNumItem { public string ApplicationType { get; set; } public int exampleId { get; set; } }
修改反序列化代码为强类型版本:
var deviceSeqNrResponse = JsonConvert.DeserializeObject<DeviceSeqNrResponse>(responseBody);
方式1:逐个属性断言(简单直接)
如果SeqNumItem的属性数量不多,直接针对每个属性编写断言(以xUnit为例):
foreach (var item in deviceSeqNrResponse.seqNum) { Assert.NotNull(item.ApplicationType); // 若有其他属性,继续添加对应的NotNull断言 }
方式2:反射遍历所有属性(通用型强)
如果属性数量较多或需要复用逻辑,用反射遍历对象的所有公开实例属性,统一检查是否为null:
using System.Reflection; foreach (var item in deviceSeqNrResponse.seqNum) { var properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in properties) { var propValue = prop.GetValue(item); Assert.NotNull(propValue, $"seqNum元素中的属性 {prop.Name} 为null"); } }
方案二:直接操作JObject(无需强类型)
如果不想定义强类型模型,用Newtonsoft.Json的JObject解析JSON,直接遍历属性进行检查:
var responseObj = JObject.Parse(responseBody); var seqNumArray = responseObj["seqNum"] as JArray; foreach (var item in seqNumArray) { foreach (var prop in item.Children<JProperty>()) { Assert.False(prop.Value.Type == JTokenType.Null, $"属性 {prop.Name} 的值为null"); } }
为什么之前的Contains方法无效?
Contains方法用于检查集合中是否包含指定元素,无法直接检测对象的属性是否为null,所以无法满足验证需求,需要针对属性值本身进行判断。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

