因工作需要,我需要獲取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);
}