zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    完全图解scrollLeft,scrollWidth,clientWidth,offsetWidth 获取相对途径,滚动图片
    Input的size,width,maxlength属性
    Linux,VI命令详解
    Javascript 第十章
    Javascript 第七章
    IE css hack
    Javascript 第九章
    js中document.documentElement 和document.body 以及其属性
    关于xmlhttp.status == 0的问题
    Javascript 第八章
  • 原文地址:https://www.cnblogs.com/XiaoLang0/p/14000366.html
Copyright © 2011-2022 走看看