VB.NET中使用Newtonsoft.Json获取JSON深层字段值的咨询
获取嵌套JSON字段值的方法
嗨,既然你已经用Newtonsoft.Json把JSON流转成字典了,那获取深层嵌套的字段其实就是逐层访问嵌套字典就好啦!我给你分步骤说清楚:
1. 获取result节点下的resolvedQuery值
因为result是主字典里的一个子字典,所以你需要先拿到这个子字典,再从中提取resolvedQuery:
// 先从主字典取出result对应的子字典,记得做类型转换 var resultDict = jsonResulttodict["result"] as Dictionary<string, object>; // 然后从result子字典里获取resolvedQuery,加?避免空引用报错 var resolvedQuery = resultDict?["resolvedQuery"]?.ToString();
如果你习惯用Item方法,也可以这么写:
var resolvedQuery = ((Dictionary<string, object>)jsonResulttodict.Item("result")).Item("resolvedQuery").ToString();
2. 获取result.metadata下的intentName值
这是两层嵌套,需要多走一步:先拿到result子字典,再取出它里面的metadata子字典,最后取intentName:
// 先拿到result子字典 var resultDict = jsonResulttodict["result"] as Dictionary<string, object>; // 再从result里取出metadata子字典 var metadataDict = resultDict?["metadata"] as Dictionary<string, object>; // 最后获取intentName var intentName = metadataDict?["intentName"]?.ToString();
用Item方法的写法是:
var intentName = ((Dictionary<string, object>)((Dictionary<string, object>)jsonResulttodict.Item("result")).Item("metadata")).Item("intentName").ToString();
小提示
我加了?空合并运算符是为了避免空引用报错——如果某个节点不存在的话,代码不会直接崩溃,而是返回null,你可以根据业务逻辑加判断处理这种情况哦!
内容的提问来源于stack exchange,提问作者Georgia Department of Insuranc
相关产品推荐
相关产品推荐

