C#利用newtonsoft.json讀取.so配置文件內容


今天花 了點時間來使用 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);
            }
        

 


免責聲明!

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



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