private static string GetExampleConfig(Dictionary <string, Type> uploaders, Dictionary <string, Type> dataSources) { string[] crontab = { "0,30 * * * * ?" }; List <SingleConfiguration> configurations = new List <SingleConfiguration>(); SingleConfiguration single = new SingleConfiguration() { name = "上传到 ", path = "/data", crontab = new HashSet <string>(crontab) }; if (uploaders.Count > 0) { var i = uploaders.First(); single.uploader = (Activator.CreateInstance(i.Value) as IUploader).GetExample() as IUploader; single.name += i.Key; } if (dataSources.Count > 0) { var i = dataSources.First(); single.dataSource = (Activator.CreateInstance(i.Value) as IDataSource).GetExample() as IDataSource; } configurations.Add(single); return(JsonConvert.SerializeObject(configurations, Formatting.Indented, new NameConverter())); }
/// <summary> /// 将Json转为SingleConfiguration类型。 /// </summary> /// <param name="reader">Json读取器</param> /// <param name="objectType">目标类型</param> /// <param name="existingValue">已存在的值</param> /// <param name="serializer">序列化生成器</param> /// <returns>SingleConfiguration实例</returns> /// <exception cref="InvalidCastException"/> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jsonObject = JObject.Load(reader); SingleConfiguration target = new SingleConfiguration() { name = jsonObject["name"].ToString(), path = jsonObject["path"].ToString(), crontab = jsonObject["crontab"].ToObject <HashSet <string> >() }; var dataSource = jsonObject["dataSource"]; if (dataSource.Type != JTokenType.Null) { string dsName = dataSource["name"].ToString(); if (_supportDataSourceTypes.ContainsKey(dsName)) { target.dataSource = jsonObject["dataSource"].ToObject(_supportDataSourceTypes[dsName]) as IDataSource; } else { throw new InvalidCastException(string.Format("没有找到\"{0}\"的数据源实现。", dsName)); } } var uploader = jsonObject["uploader"]; string uploaderName = uploader["name"].ToString(); if (_supportUploaderTypes.ContainsKey(uploaderName)) { target.uploader = jsonObject["uploader"].ToObject(_supportUploaderTypes[uploaderName]) as IUploader; } else { throw new InvalidCastException(string.Format("没有找到\"{0}\"的上传实现。", uploaderName)); } return(target); }