Example #1
0
        private static ITypeNameResolver CreateTypeNameResolverFromAttributes(Type type)
        {
            JsonTypeNameAttribute[] attributes = JsonTypeNameAttribute.GetKnownTypes(type);
            if (attributes == null)
            {
                throw new Exception($"Type {type} is not supported by {nameof(TypedConverter)} due to missing {nameof(JsonTypeNameAttribute)}s.");
            }

            Type baseType = FindBaseClass(type);

            TypeNameResolver resolver = new TypeNameResolver();

            foreach (var attribute in attributes)
            {
                if (!baseType.IsAssignableFrom(attribute.Type))
                {
                    throw new Exception($"Type '{attribute.Type}' cannot be assigned a name using the {nameof(JsonTypeNameAttribute)} because it does not inherit from '{type}'.");
                }

                if (attribute.TypeName == null)
                {
                    if (resolver.DefaultType != null)
                    {
                        throw new Exception($"Type '{attribute.Type}' and '{resolver.DefaultType}' cannot both be the default type when serializaing '{baseType}'.");
                    }

                    resolver.DefaultType = attribute.Type;
                }
                else
                {
                    resolver.AddType(attribute.TypeName, attribute.Type);
                }
            }
            return(resolver);
        }
 /// <summary>
 /// Checks, whether this converter factory is capable of converting the
 /// given type.
 /// </summary>
 /// <param name="type">The type to check.</param>
 /// <returns>true, if this converter factory can create a converter for
 /// the given type; false, otherwise.</returns>
 public bool CanConvert(Type type)
 {
     return(JsonTypeNameAttribute.GetKnownTypes(type) != null);
 }