using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace AgileConfig.Server.Common { public class DictionaryConvertToJson { public static string ToJson(IDictionary dict) { Dictionary root = new Dictionary(); foreach (var kv in dict) { Generate(kv.Key, kv.Value, root); } return DictToJsonString(root); } private static string DictToJsonString(Dictionary dict) { return JsonConvert.SerializeObject(dict, Formatting.Indented); } /// /// 把扁平化的键值对还原成字典嵌套字典的模式 /// /// /// /// private static void Generate(string key, string value, Dictionary parent) { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key)); } var groupArr = key.Split(':'); if (groupArr.Length > 1) { var sonKey = groupArr[0]; var newArr = new string[groupArr.Length - 1]; for (int i = 1; i < groupArr.Length; i++) { newArr[i - 1] = groupArr[i]; } var otherKeys = string.Join(':', newArr); if (parent.ContainsKey(sonKey)) { //如果已经有子字典 var son = parent[sonKey] as Dictionary; if (son != null) { Generate(otherKeys, value, son); } } else { var son = new Dictionary(); Generate(otherKeys, value, son); parent.Add(sonKey, son); } } else { parent.Add(key, value); } } } }