Json配置
Json的作用
一套代码,适配不同环境】
同一个程序,要在 3 个地方跑:
你自己电脑(开发环境)
公司测试服务器(测试环境)
客户线上服务器(生产环境)
这 3 个地方的「数据库地址、接口地址、日志开关」全不一样,怎么办?
写 3 套代码?太蠢了
用 JSON 配置:给 3 个环境各写一个 JSON 文件,代码完全不用改,读不同的配置文件就行
// 1. 引入必需的库(就像工具包,没有这些无法读写文件/JSON)
using System;
using System.IO;
using Newtonsoft.Json;
// 2. 配置类:定义JSON的结构(告诉程序JSON里有哪些数据)
public class AppConfig
{
// 数据库连接地址
public string DbConnection { get; set; }
// 数据库端口
public int DbPort { get; set; }
// 是否自动运行
public bool AutoRun { get; set; }
// 日志保存路径
public string LogPath { get; set; }
// 嵌套的用户信息(JSON里可以包含子对象)
public UserInfo User { get; set; }
}
// 3. 用户信息子类(嵌套在AppConfig里)
public class UserInfo
{
// 用户名
public string Name { get; set; }
// 密码
public string Pwd { get; set; }
}
// 4. 通用JSON工具类:封装读写方法(重复使用,不用每次写代码)
public static class JsonConfig
{
///
/// 保存对象到JSON文件
///
public static void Save
{
// 序列化:把C#对象 转换成 格式化的JSON字符串
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
// 把JSON字符串写入文件
File.WriteAllText(path, json);
}
///
/// 从JSON文件读取数据,转回C#对象
///
public static T Load
{
// 如果文件不存在,返回空
if (!File.Exists(path))
return default;
// 读取文件所有文本
string json = File.ReadAllText(path);
// 反序列化:把JSON字符串 转回 C#对象
return JsonConvert.DeserializeObject
}
}
// 5. 程序主入口(程序从这里开始运行)
class Program
{
static void Main(string[] args)
{
// ===================== 第一步:创建配置数据 =====================
// 新建一个配置对象,手动赋值
AppConfig config = new AppConfig
{
DbConnection = "localhost",
DbPort = 3306,
AutoRun = true,
LogPath = "logs/",
User = new UserInfo { Name = "admin", Pwd = "123456" }
};
// ===================== 第二步:写入JSON配置文件 =====================
// 调用工具类,把配置对象保存为 config.json 文件
JsonConfig.Save(config);
Console.WriteLine("JSON配置文件已写入成功!\n");
// ===================== 第三步:读取JSON配置文件 =====================
// 调用工具类,从文件读取数据,转回配置对象
AppConfig readConfig = JsonConfig.Load
// ===================== 第四步:打印读取到的数据 =====================
Console.WriteLine("读取到的配置信息:");
Console.WriteLine("数据库地址:" + readConfig.DbConnection);
Console.WriteLine("数据库端口:" + readConfig.DbPort);
Console.WriteLine("是否自动运行:" + readConfig.AutoRun);
Console.WriteLine("日志路径:" + readConfig.LogPath);
Console.WriteLine("用户名:" + readConfig.User.Name);
Console.WriteLine("密码:" + readConfig.User.Pwd);
// 让程序暂停,方便查看结果
Console.ReadLine();
}
}

浙公网安备 33010602011771号