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。

posted @ 2018-08-22 16:11  MemoryPro  阅读(2123)  评论(0编辑  收藏  举报