CSharp读取json配置文件内容


步骤

  1. 读取配置文件转换成字符串,代码如下
 string contents = System.IO.File.ReadAllText("config.json");

注意:该语句会抛出文件不存在异常。

  1. 使用Newtonsoft.Json将json字符串转换成类的对象,完整代码如下所示
 public class Init
    {
        public static InitInfo init = new InitInfo();
        public Init(){
            try
            {
                string contents = System.IO.File.ReadAllText("config.json");
                //Shell.WriteLine("ini 配置文件\r\n" + JsonConvert.SerializeObject(init));
                init = JsonConvert.DeserializeObject<InitInfo>(contents);
                Shell.WriteLine("初始化配置文件内容\r\n\r\n" + contents + "\r\n\r\n");
            }
            catch (Exception)
            {
                throw;
            }
            
        }
    }

注意事项

  • Newtonsoft.Json 需要添加引用,下载地址如下所示
    https://www.newtonsoft.com/json

  • 可以使用 JsonConvert.SerializeObject(init)语句生成配置信息,打印在控制台,C-V。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM