C#递归获取JSON所有键值对


因工作需要,我需要获取JSON所有键值对。

这里我使用List存储,因为有键冲突,但是要求是所有键值对都需要,不理会冲突,所以没有使用字典。

public static List<string> GetSignStr(string json, List<string> strList)
{
json = json.Replace("\r\n", string.Empty);
json = json.Replace("[", string.Empty);
json = json.Replace("]", string.Empty);
JObject o = JObject.Parse(json);
foreach (var x in o)
{
if (x.Value.GetType() == typeof(JObject) || (x.Value.GetType() == typeof(JArray)))
GetSignStr(x.Value.ToString(), strList);//递归
else
strList.Add(x.Key + "=" + x.Value.ToString() + "&");//这里x.Key则为键,x.Value为值。可以选择使用字典
}
return strList;
}

传入的是JSON字符串,以及一个存储的List。

调用方式:

List<string> listStr = new List<string>();//
listStr = GetSignStr(jsonStr, listStr);

 

 

补充:

定义一个键值对的类进行存储:

public class KeyValue
{
public string key { get; set; }
public string value { get; set; }
}

public static List<KeyValue> DG(string json,List<KeyValue> strList)
{
json=json.Replace("\r\n",string.Empty);
json = json.Replace("[", string.Empty);
json = json.Replace("]", string.Empty);
var o = JObject.Parse(json);
foreach (var x in o)
{
if (x.Value.GetType() == typeof(JObject) || (x.Value.GetType() == typeof(JArray)))
{
DG(x.Value.ToString(), strList);
}
else
{
KeyValue keyValue = new KeyValue();
keyValue.key = x.Key;
keyValue.value = x.Value.ToString();
strList.Add(keyValue);
}

}
return strList;
}

调用方式:

 string json=“”;//这个为你要解析的JSON字符串

List<KeyValue> jsonList = new List<KeyValue>();
jsonList = DG(json,jsonList);

结果图:

遍历出来想怎么样就是你的事了。

 

foreach (var tmp in jsonList)
{
Console.WriteLine(tmp.key+":"+tmp.value);
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM