如果只是想把Json轉成key value的話,對於復雜的json,有時候jsonconvert轉換不成功.
在網上找到一個利用正則表達式轉字典的帖子,但現在找不到原帖了.
該帖子是把json的所有嵌套對像均轉換成鍵值對形式.該帖子中@"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)")正則表達式未考慮小數點的情況,
在此做一個修改@"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|(\-|\+)?\d+(\.\d+)?)".
在寫反射時,需要把json轉換成方法的參數,因此只需解析出最外層的對象即可.
以下是兩種解析方式:
1.只解析最外層對象
/// <summary>
/// Json格式轉換成鍵值對,鍵值對中的Key需要區分大小寫 ,不考慮json本身就是一個數組的形式
/// </summary>
/// <param name="JsonData">需要轉換的Json文本數據</param>
/// <returns></returns>
public static Dictionary<string, object> ToDictionary(string JsonData)
{
object Data = null;
Dictionary<string, object> Dic = new Dictionary<string, object>();
MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|(\-|\+)?\d+(\.\d+)?)");//使用正則表達式匹配出JSON數據中的鍵與值
foreach (Match item in Match)
{
try
{
if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果數據為null(字符串類型),直接轉換成null
else Data = item.Groups[2].ToString(); //數據為數字、字符串中的一類,直接寫入
Dic.Add(item.Groups[1].ToString(), Data);
}
catch { }
}
return Dic;
}
2.解析所有嵌套的對象(遞歸實現)
/// <summary>
/// Json格式轉換成鍵值對,鍵值對中的Key需要區分大小寫
/// </summary>
/// <param name="JsonData">需要轉換的Json文本數據</param>
/// <returns></returns>
public static Dictionary<string, object> ToDictionary(string JsonData)
{
object Data = null;
Dictionary<string, object> Dic = new Dictionary<string, object>();
if (JsonData.StartsWith("["))
{
//如果目標直接就為數組類型,則將會直接輸出一個Key為List的List<Dictionary<string, object>>集合
//使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正則表達式匹配出JSON數組
foreach (Match ListItem in ListMatch)
{
List.Add(ToDictionary(ListItem.ToString()));//遞歸調用
}
Data = List;
Dic.Add("List", Data);
}
else
{
MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|(\-|\+)?\d+(\.\d+)?*)");//使用正則表達式匹配出JSON數據中的鍵與值
foreach (Match item in Match)
{
try
{
if (item.Groups[2].ToString().StartsWith("["))
{
//如果目標是數組,將會輸出一個Key為當前Json的List<Dictionary<string, object>>集合
//使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正則表達式匹配出JSON數組
foreach (Match ListItem in ListMatch)
{
List.Add(ToDictionary(ListItem.ToString()));//遞歸調用
}
Data = List;
}
else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果數據為null(字符串類型),直接轉換成null
else Data = item.Groups[2].ToString(); //數據為數字、字符串中的一類,直接寫入
Dic.Add(item.Groups[1].ToString(), Data);
}
catch { }
}
}
return Dic;
}
