快速读取json文件的方式
- 声明一个类,存放配置文件里面的变量
public class MNT_Config
{
//若要以静态变量的方式调用,则在里面声明一个静态的变量
public static MNT_Config instance { get; set; }
/// <summary>
/// 串口号;
/// </summary>
public string COM { get; set; }
public long Baudrate { get; set; }
public int ReportTimeOut { get; set; }
public List<LanguageSetting> Language { get; set; }
}
public class LanguageSetting
{
public string name { get; set; }
public string value { get; set; }
//通信时需要转换为字节数
public byte[] HexStringToByteArray()
{
string str = value.Replace(" ", "");
byte[] array = new byte[str.Length / 2];
for (int i = 0; i < str.Length; i += 2)
{
array[i / 2] = Convert.ToByte(str.Substring(i, 2), 16);
}
return array;
}
}
- 读取config函数
StreamReader file = File.OpenText(LocalPath.localpath + "\\MNT_Config.json");
string josn = file.ReadToEnd();
MNT_Config.instance = JsonConvert.DeserializeObject<MNT_Config>(josn);
//
foreach(LanguageSetting lang in MNT_Config.instance.Language)
{
ShopList.Items.Add(lang.name);
}
注意:
类里面的变量名字必须与配置文件完全一致,不然序列化值为空