C#jsonのあるkeyに対応する値を取得し、反復をサポートする
1688 ワード
///
/// json key value
///
///
///
///
public string GetJsonValue(string strJson , string key)
{
// :
//strJson = @"{'1':{'id':{'ip':'192.168.0.1','p':34,'pass':'ff','port':80,'user':'t'}},'code':0}";
//key = "user"
string strResult="";
JObject jsonObj = JObject.Parse(strJson);
strResult = GetNestJsonValue(jsonObj.Children(), key);
return strResult;
}
///
/// eky
///
///
///
///
public string GetNestJsonValue(JEnumerable jToken, string key)
{
IEnumerator enumerator = jToken.GetEnumerator();
while (enumerator.MoveNext())
{
JToken jc = (JToken)enumerator.Current;
if (jc is JObject || ((JProperty)jc).Value is JObject)
{
return GetNestJsonValue(jc.Children(), key);
}
else
{
if (((JProperty)jc).Name == key)
{
return ((JProperty)jc).Value.ToString();
}
}
}
return null;
}
リファレンスhttps://www.cnblogs.com/feiyuhuo/p/6098065.html