public override Object ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer) { Object obj = serializer.Deserialize(reader, MakeGenericType(objectType)); if (obj is null) { return(null); } Type type = obj.GetType(); if (!type.IsGenericType) { return(obj); } if (type.GetGenericTypeDefinition() != DictionaryTypeDifinition) { return(obj); } Type[] generic = type.GetGenericArguments()[1].GetGenericArguments(); Type tree = DictionaryTreeTypeDifinition.MakeGenericType(generic); ConstructorInfo method = tree.GetConstructor(new[] { DictionaryTypeDifinition.MakeGenericType(generic[0], DictionaryTreeNodeTypeDifinition.MakeGenericType(generic)), IEqualityComparerTypeDifinition.MakeGenericType(generic[0]) }); return(method?.Invoke(new[] { obj, null })); }
protected virtual Type MakeGenericType(Type objectType) { try { if (!objectType.IsGenericType) { return(objectType); } Type definition = objectType.GetGenericTypeDefinition(); if (definition == IEqualityComparerTypeDifinition) { return(EqualityComparerTypeDifinition.MakeGenericType(objectType.GetGenericArguments())); } if (definition == DictionaryTreeTypeDifinition || definition == IDictionaryTreeTypeDifinition) { Type[] generic = objectType.GetGenericArguments(); return(DictionaryTypeDifinition.MakeGenericType(generic[0], DictionaryTreeNodeTypeDifinition.MakeGenericType(generic[0], generic[1]))); } return(objectType); } catch (Exception exception) { throw new JsonSerializationException($"Unable to construct concrete type from generic {objectType}", exception); } }