Json文件与C#字典读写转换

1.C# 字典读取Json文件:

 1 Dictionary<string, Dictionary<string, float>> Dic_Infos = new Dictionary<string, Dictionary<string, float>>();
 2 
 3 string path = @"D:Infos.json";
 4 
 5 private void ReadJson()
 6 { 
 7     StreamReader SR = File.OpenText(path);
 8     JsonTextReader JTR = new JsonTextReader(SR);
 9     JToken JTokens = JToken.ReadFrom(JTR);
10     int num = JTokens.Count();
11     if (num>0)
12     {
13         JToken first = JTokens.First();
14 
15         for (int i = 0; i < num; i++)
16         {
17             string Name = first.Path.Substring(2, first.Path.Length - 4);
18 
19             string Info = first.First().ToString();
20             Dictionary<string, float> Dic_Info = JsonConvert.DeserializeObject<Dictionary<string, float>>(Info);
21             if (!Dic_Infos.ContainsKey(Name))
22             {
23                 Dic_Infos.Add(Name, Dic_Info);
24             }
25             first = first.Next;
26         }
27     } 
28 }

2.C# 字典写入Json文件:

 1 private void WriteJson()
 2 {  
 3     string Json = "{";
 4     foreach (var item in Dic_Infos)
 5     {
 6         Json += """ + item.Key + "":{";
 7         foreach (var items in item.Value)
 8         {
 9             Json += """ + items.Key + "":" + """ + items.Value + "",";
10         }
11         Json += "},";
12     }
13     Json += "}";
14 
15     JToken JToken = (JToken)JsonConvert.DeserializeObject(Json);
16     string output = Newtonsoft.Json.JsonConvert.SerializeObject(JToken, Newtonsoft.Json.Formatting.Indented);
17     File.WriteAllText(path, output); 
18 }
支持个人观看使用,如商用或转载,请告知! -----萧朗(QQ:453929789 Email:xiaolang_xl@sina.com)
原文地址:https://www.cnblogs.com/XiaoLang0/p/14000366.html