using System;
using System.Reflection;
namespace Utf8Json.Resolvers
{
///
/// Get formatter from [JsonFormatter] attribute.
///
public sealed class AttributeFormatterResolver : IJsonFormatterResolver
{
public static IJsonFormatterResolver Instance = new AttributeFormatterResolver();
AttributeFormatterResolver()
{
}
public IJsonFormatter GetFormatter()
{
return FormatterCache.formatter;
}
static class FormatterCache
{
public static readonly IJsonFormatter formatter;
static FormatterCache()
{
#if (UNITY_METRO || UNITY_WSA) && !NETFX_CORE
var attr = (JsonFormatterAttribute)typeof(T).GetCustomAttributes(typeof(JsonFormatterAttribute), true).FirstOrDefault();
#else
var attr = typeof(T).GetTypeInfo().GetCustomAttribute();
#endif
if (attr == null)
{
return;
}
try
{
if (attr.FormatterType.IsGenericType && !attr.FormatterType.GetTypeInfo().IsConstructedGenericType)
{
var t = attr.FormatterType.MakeGenericType(typeof(T)); // use T self
formatter = (IJsonFormatter)Activator.CreateInstance(t, attr.Arguments);
}
else
{
formatter = (IJsonFormatter)Activator.CreateInstance(attr.FormatterType, attr.Arguments);
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Can not create formatter from JsonFormatterAttribute, check the target formatter is public and has constructor with right argument. FormatterType:" + attr.FormatterType.Name, ex);
}
}
}
}
}