本人从其它网站获取信息,接收到一串JSON,本人只想取其distance中的值, JavaScriptSerializer jss=new JavaScriptSerializer();
Dictionary<string, object> ar = (Dictionary<string, object>)jss.DeserializeObject(str);
foreach (var _a in ar)
{
if (_a.Key == “result”)
foreach (var _b in (Dictionary<string, object>)_a.Value)///此处断点显示的是 _a.Value count=4可以强类型转换
{
if (_b.Key == “routes”)
{
foreach (var _c in (Dictionary<string, object>)_b.Value)//此处断点显示 _b.Value object[1] 这里转换失败,退出
{
foreach (var _d in (Dictionary<string, object>)_c.Value)
if (_d.Key == “distance”)
str = Convert.ToString(_d.Value);
}
}
}
讨教 foreach (var _c in (Dictionary<string, object>)_b.Value)这个地方要怎么修改?
}
Dictionary<string, object> ar = (Dictionary<string, object>)jss.DeserializeObject(str);
foreach (var _a in ar)
{
if (_a.Key == “result”)
foreach (var _b in (Dictionary<string, object>)_a.Value)///此处断点显示的是 _a.Value count=4可以强类型转换
{
if (_b.Key == “routes”)
{
foreach (var _c in (Dictionary<string, object>)_b.Value)//此处断点显示 _b.Value object[1] 这里转换失败,退出
{
foreach (var _d in (Dictionary<string, object>)_c.Value)
if (_d.Key == “distance”)
str = Convert.ToString(_d.Value);
}
}
}
讨教 foreach (var _c in (Dictionary<string, object>)_b.Value)这个地方要怎么修改?
}
解决方案
8
题主请发json,再贴代码。
8
弄个实体类来处理吧。清晰明了
14
对,还是用实体类。简单生成方法:将json复制到粘贴板,在项目里新建一个空cs文件,或打开已有的cs,依次选择菜单:编辑-》选择性粘贴-》将Json粘贴为类,将会生成json对应的实体类