今天花 了點時間來使用 C#讀取json檔案 ,檔案后綴為 .so檔案 ,也是基于檔案流的形式 獲取 物件 ,然后決議;
之所以嘗試 使用 json讀取 ,是因為其組態檔的格式 更為友好 和方便,直觀 且形象,當然 XML也是很方便的;
主要是多了一種讀取 組態檔的方式;特記錄下來,方便后續專案實際使用;
格式如圖:

需要注意的是這種格式需注意編輯;
當然通過代碼初始化和寫入的話,會自動生成如上的格式的,本文只完成如何讀取組態檔的資訊;
參考的程式集如:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Linq;
//獲取 jobject的物件,及讀取鍵值的方法
class JsonConfigHelper { public JObject jObject = null; public string this[string key] { get { string str = ""; if (jObject != null) { str = GetValue(key); } return str; } } public JsonConfigHelper(string path) { jObject = new JObject(); using (System.IO.StreamReader file = System.IO.File.OpenText(path)) { using (JsonTextReader reader = new JsonTextReader(file)) { jObject = JObject.Load(reader); } }; } public T GetValue<T>(string key) where T : class { return JsonConvert.DeserializeObject<T>(jObject.SelectToken(key).ToString()); } public string GetValue(string key) { return Regex.Replace((jObject.SelectToken(key).ToString()), @"\s", ""); } }
讀取不同格式的鍵的內容的方法:
try { JObject myjobj; JsonConfigHelper helper = new JsonConfigHelper(filepath); myjobj = helper.jObject as JObject;//獲取Jobject物件 int i = myjobj.Count; //當前物件的節點的數量 string str5 = (string)myjobj["sex"];//直接讀取當前鍵值 MessageBox.Show(str5); JObject myjobj666; myjobj666 = myjobj["Colleague"]["財務部"] as JObject;//當前節點下的子節點作為jobject物件 //實際測驗程序中會例外報錯未實體化,這是因為配件檔案的保存格式問題,UTF-8 string str3 = (string)myjobj666["account"]; MessageBox.Show(str3); string str1 = helper["SOCLASS[0].Name"];// MessageBox.Show(str1); JToken jken = myjobj["SOCLASS"];//鍵物件["SO"]記憶體在多組資料,讀取的格式 foreach (JObject myobject in jken) { string strr = (string)myobject["Name"];//讀取每組節點下的某個鍵值的資料 MessageBox.Show(strr); } if (myjobj.ContainsKey("SOCLASS")) //判斷jobject物件中是否存在"SO"這個鍵物件 { MessageBox.Show("done"); } } catch (Exception ex) { MessageBox.Show(ex.Message); }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/114244.html
標籤:C#
