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);

猜你喜欢

转载自www.cnblogs.com/tofumoxi/p/10736109.html