使用遞歸函數,你可以做到這一點,支持任意數量的「關鍵水平」的(任何數量的點)
功能:
private static void SetValues(string[] keys, int keyIndex, string value, IDictionary<string, object> parentDic)
{
var key = keys[keyIndex];
if (keys.Length > keyIndex + 1)
{
object childObj;
IDictionary<string, object> childDict;
if (parentDic.TryGetValue(key, out childObj))
{
childDict = (IDictionary<string, object>)childObj;
}
else
{
childDict = new Dictionary<string, object>();
parentDic[key] = childDict;
}
SetValues(keys, keyIndex + 1, value, childDict);
}
else
{
parentDic[key] = value;
}
}
實施例:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("User.Info", "Your info");
dict.Add("User.Profile", "Profile");
dict.Add("Menu.System.Task", "Tasks");
dict.Add("Menu.System.Configuration.Number", "1");
dict.Add("Menu.System.Configuration.Letter", "A");
var outputDic = new Dictionary<string, object>();
foreach (var kvp in dict)
{
var keys = kvp.Key.Split('.');
SetValues(keys, 0, kvp.Value, outputDic);
}
var json = JsonConvert.SerializeObject(outputDic);
輸出:
{
"User": {
"Info": "Your info",
"Profile": "Profile"
},
"Menu": {
"System": {
"Task": "Tasks",
"Configuration": {
"Number": "1",
"Letter": "A"
}
}
}
}
這應該是一個評論不是答案。 ! –