C# 讀取Json配置文件


今天需要用到讀取Json配置文件的helper   結果竟然沒找到合適的    微軟自己有一個 不過不支持.Net fw 4.0

於是自己在NewTonSoft.Json的基礎上  加了點小小的封裝   沒做異常處理 后續更新會來更博

 

 

 

 

 1     public class JsonConfigHelper
 2     {
 3         private JObject jObject = null;
 4         public string this[string key]
 5         {
 6             get
 7             {
 8                 string str = "";
 9                 if (jObject != null)
10                 {
11                     str = GetValue(key);
12                 }
13                 return str;
14             }
15         }
16         public JsonConfigHelper(string path)
17         {
18             jObject = new JObject();
19             using (System.IO.StreamReader file = System.IO.File.OpenText(path))
20             {
21                 using (JsonTextReader reader = new JsonTextReader(file))
22                 {
23                     jObject = JObject.Load(reader);
24                 }
25             };
26         }
27         public T GetValue<T>(string key) where T : class
28         {
29             return JsonConvert.DeserializeObject<T>(jObject.SelectToken(key).ToString());
30         }
31         public string GetValue(string key) 
32         {
33             return Regex.Replace((jObject.SelectToken(key).ToString()), @"\s", "");
34         }
35     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM