public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JContainer lJContainer = default(JContainer); if (reader.TokenType == JsonToken.StartObject) { lJContainer = JObject.Load(reader); var typeName = GetTypeNameFromToken(lJContainer); var builtType = Type.GetType($"{NamespacePrefix}{typeName}"); if (builtType == null) { //try and find using reflection builtType = typeof(Thing).Assembly.GetTypes().FirstOrDefault(p => p.Name.Equals(typeName, StringComparison.OrdinalIgnoreCase)); } if (builtType == null) { builtType = typeof(Thing); } existingValue = Convert.ChangeType(existingValue, builtType); existingValue = Activator.CreateInstance(builtType); serializer.Populate(lJContainer.CreateReader(), existingValue); } return(existingValue); }
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { Type genericTypeDefinition = objectType.GetGenericTypeDefinition(); Type genericArgument = objectType.GetGenericArguments()[0]; Type constructed = genericTypeDefinition.MakeGenericType(genericArgument); var wrapper = Activator.CreateInstance(constructed); Type instanceType = typeof(List <>).MakeGenericType(genericArgument); var targetItems = Activator.CreateInstance(instanceType); JContainer jObject = JArray.Load(reader); if (targetItems != null) { serializer.Populate(jObject.CreateReader(), targetItems); } CheckAndSetItemsList(genericArgument, wrapper, targetItems); return(wrapper); }
/// <summary> /// 初始化配置,默认加载JSON文本并填充当前对象。 /// </summary> /// <param name="data">配置内容</param> /// <returns>是否加载成功</returns> public virtual bool Initialize(JContainer data) { using (var reader = data.CreateReader()) { var serializer = new JsonSerializer(); serializer.Populate(reader, this); return(true); } }