当前位置: 移动技术网 > IT编程>开发语言>c# > C#利用newtonsoft.json读取.so配置文件内容

C#利用newtonsoft.json读取.so配置文件内容

2019年10月29日  | 移动技术网IT编程  | 我要评论

今天花 了点时间来使用 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);
            }
        

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网