使用JSON.Net(VB)检查JObject子键是否存在的方法
正确判断JObject深层子对象是否存在的方法
针对你提供的JObject结构:
{"widgets":{"collect_survey":{"ToCountry":"US"},"details":{"ToCountry":"US"},"check_survey":{}}}
以下是几种可行的实现方式:
方法1:逐层判断键是否存在
先确认父对象存在,再判断子对象的键:
Dim _res As JObject = Execution.Context ' 先检查widgets存在且不是null,再检查collect_survey是否存在 Dim hasCollectSurvey As Boolean = _res.ContainsKey("widgets") AndAlso _res("widgets").Type <> JTokenType.Null AndAlso DirectCast(_res("widgets"), JObject).ContainsKey("collect_survey")
方法2:使用SelectToken直接定位(推荐)
SelectToken支持点分隔的路径表达式,直接定位目标子对象,判断返回结果是否不为Nothing:
Dim _res As JObject = Execution.Context ' 判断widgets.collect_survey是否存在 Dim hasCollectSurvey As Boolean = _res.SelectToken("widgets.collect_survey") IsNot Nothing ' 如果要判断更深层的节点,比如widgets.collect_survey.ToCountry Dim hasToCountry As Boolean = _res.SelectToken("widgets.collect_survey.ToCountry") IsNot Nothing
为什么你的原有代码不可行?
_res.ContainsKey("widgets.collect_survey"):ContainsKey仅能判断当前JObject的直接子键,不支持点分隔的嵌套路径。_res("widgets").ContainsKey("widgets"):_res("widgets")对应的是widgets这个子JObject,它的直接子键里没有widgets,所以必然返回False。
内容的提问来源于stack exchange,提问作者DDulla
相关产品推荐
相关产品推荐

