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 配置文件
" + JsonConvert.SerializeObject(init));
                init = JsonConvert.DeserializeObject<InitInfo>(contents);
                Shell.WriteLine("初始化配置文件内容

" + contents + "

");
            }
            catch (Exception)
            {
                throw;
            }
            
        }
    }

注意事项

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

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

原文地址:https://www.cnblogs.com/memorypro/p/9518363.html