Using a recursive function you can do this, supporting any number of "key levels" (any number of dots)
Function:
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; } }
Example:
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);
Output:
{ "User": { "Info": "Your info", "Profile": "Profile" }, "Menu": { "System": { "Task": "Tasks", "Configuration": { "Number": "1", "Letter": "A" } } } }