错误描述
在一次开发中,使用了JSON数据作为配置文件,但反序列化时总是出错,开始还以为是转义字符的问题,因为存了一个绝对路径(D:xxxx.json),后来测试发现竟然发现是类嵌套的问题。
解决方法
在JSON反序列化时,如果存在嵌套类,需要把嵌套的类写到包裹类里面去,并且在反序列化时传入包裹类的类型。
JSON配置文件类代码
public class SettingsHelper { private static string path = "settings.json"; /// <summary> /// 读取配置 /// </summary> /// <returns></returns> public static Settings ReadSettings() { Settings settings = new Settings(); if (File.Exists(path)) { string buffer = System.IO.File.ReadAllText(path); settings = (Settings)JsonHelper.Deserialize(buffer,typeof(Settings)); } return settings; } /// <summary> /// 保存配置 /// </summary> /// <param name="settings"></param> public static void WriteSettings(Settings settings) { string buffer = JsonHelper.Serialize(settings); System.IO.File.WriteAllText(path, buffer); } } [Serializable] public class Settings { /// <summary> /// 时间间隔 /// </summary> public int TimeInterval { get; set; } /// <summary> /// 淘宝助手数据库目录 /// </summary> public string ApptradePath { get; set; } /// <summary> /// 数据库服务器地址 /// </summary> public string SqlServer { get; set; } /// <summary> /// 数据库账号 /// </summary> public string SqlUid { get; set; } /// <summary> /// 数据库密码 /// </summary> public string SqlPassword { get; set; } /// <summary> /// 数据库名称 /// </summary> public string SqlDatabase { get; set; } /// <summary> /// 数据库表间映射关系集合 /// </summary> public List<TableMaping> TableMapings { get; set; } public Settings() { ApptradePath = string.Empty; SqlServer = string.Empty; SqlUid = string.Empty; SqlPassword = string.Empty; SqlDatabase = string.Empty; TableMapings = new List<TableMaping>(); } [Serializable] public class TableMaping { /// <summary> /// 源表名主键(用于删除数据) /// </summary> [Required(ErrorMessage="必须填写数据源表主键。")] public string SourceTablePrimaryKey { get; set; } /// <summary> /// 数据源源表名称 /// </summary> [Required(ErrorMessage = "必须填写数据源表名称。")] public string SourceTableName { get; set; } /// <summary> /// 数据源表字段 /// </summary> [Required(ErrorMessage = "必须填写数据源表字段。")] public string SourceFields { get; set; } /// <summary> /// 目标数据源表名称 /// </summary> [Required(ErrorMessage = "必须填写目标数据源表名称。")] public string TargetTableName { get; set; } /// <summary> /// 目标表字段 /// </summary> [Required(ErrorMessage = "必须填写目标表字段。")] public string TargetFields { get; set; } public TableMaping() { SourceTablePrimaryKey = string.Empty; SourceTableName = string.Empty; SourceFields = string.Empty; TargetFields = string.Empty; TargetTableName = string.Empty; } } }
反序列化代码
/// <summary> /// 反序列化字符串,返回对象。 /// </summary> /// <param name="json"></param> /// <returns></returns> public static object Deserialize(string json,Type type) { object val= JsonConvert.DeserializeObject(json,type); return val; }