最近项目中有很多调用Api的地方,本来是打算写实体类把返回的JSON转实体类,但接口太多,好多还是不常用的就自己写了一个查找JSON中指定Key的Value。代码仅供参考,只是一个草版,希望大家多给给意见。
#region 传入指定json字符串和key值查找传入key的value(object)
public static object digui(string json, string key)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
Dictionary<string, object> js = javaScriptSerializer.DeserializeObject(json) as Dictionary<string, object>;
object value = null;
foreach (KeyValuePair<string, object> item in js)
{
if (item.Key == key)
{
value = item.Value;
break;
}
else if (item.Value is Dictionary<string, object>)
{
object se = di(item.Value as Dictionary<string, object>, key);
if (se != null)
{
value = se;
break;
}
}
else if (item.Value is object[])
{
object[] se = item.Value as object[];
if (se.Length > 0)
{
foreach (object o in se)
{
if (o is Dictionary<string, object>)
{
object ses = di(item.Value as Dictionary<string, object>, key);
if (ses != null)
{
value = ses;
break;
}
}
}
}
}
}
return value;
}
private static object di(Dictionary<string, object> dic, string key)
{
object vale = null;
foreach (KeyValuePair<string, object> item in dic)
{
if (item.Key == key)
{
vale = item.Value;
break;
}
else if (item.Value is Dictionary<string, object>)
{
object fan = di(item.Value as Dictionary<string, object>, key);
if (fan != null)
{
vale = fan;
break;
}
}
else if (item.Value is object[])
{
object[] se = item.Value as object[];
if (se.Length > 0)
{
foreach (object o in se)
{
if (o is Dictionary<string, object>)
{
object ses = di(o as Dictionary<string, object>, key);
if (ses != null)
{
vale = ses;
break;
}
}
}
}
}
}
return vale;
}
#endregion