2 // Copyright (c) 2007 James Newton-King
4 // Permission is hereby granted, free of charge, to any person
5 // obtaining a copy of this software and associated documentation
6 // files (the "Software"), to deal in the Software without
7 // restriction, including without limitation the rights to use,
8 // copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the
10 // Software is furnished to do so, subject to the following
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18 // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20 // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 // OTHER DEALINGS IN THE SOFTWARE.
27 using System.ComponentModel;
28 using System.Globalization;
30 using System.Reflection;
31 using System.Runtime.Serialization;
32 using System.Security.Permissions;
33 using Newtonsoft.Json.Utilities;
35 namespace Newtonsoft.Json.Serialization
37 #if !SILVERLIGHT && !PocketPC && !NET20
38 internal interface IMetadataTypeAttribute
40 Type MetadataClassType { get; }
44 internal static class JsonTypeReflector
46 public const string IdPropertyName = "$id";
47 public const string RefPropertyName = "$ref";
48 public const string TypePropertyName = "$type";
49 public const string ArrayValuesPropertyName = "$values";
51 public const string ShouldSerializePrefix = "ShouldSerialize";
52 public const string SpecifiedPostfix = "Specified";
54 private static readonly ThreadSafeStore<ICustomAttributeProvider, Type> JsonConverterTypeCache = new ThreadSafeStore<ICustomAttributeProvider, Type>(GetJsonConverterTypeFromAttribute);
55 #if !SILVERLIGHT && !PocketPC && !NET20
56 private static readonly ThreadSafeStore<Type, Type> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type>(GetAssociateMetadataTypeFromAttribute);
58 private const string MetadataTypeAttributeTypeName =
59 "System.ComponentModel.DataAnnotations.MetadataTypeAttribute, System.ComponentModel.DataAnnotations, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
60 private static Type _cachedMetadataTypeAttributeType;
63 private static readonly ThreadSafeStore<ICustomAttributeProvider, Type> TypeConverterTypeCache = new ThreadSafeStore<ICustomAttributeProvider, Type>(GetTypeConverterTypeFromAttribute);
65 private static Type GetTypeConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider)
67 TypeConverterAttribute converterAttribute = GetAttribute<TypeConverterAttribute>(attributeProvider);
68 if (converterAttribute == null)
71 return Type.GetType(converterAttribute.ConverterTypeName);
74 private static Type GetTypeConverterType(ICustomAttributeProvider attributeProvider)
76 return TypeConverterTypeCache.Get(attributeProvider);
80 public static JsonContainerAttribute GetJsonContainerAttribute(Type type)
82 return CachedAttributeGetter<JsonContainerAttribute>.GetAttribute(type);
85 public static JsonObjectAttribute GetJsonObjectAttribute(Type type)
87 return GetJsonContainerAttribute(type) as JsonObjectAttribute;
90 public static JsonArrayAttribute GetJsonArrayAttribute(Type type)
92 return GetJsonContainerAttribute(type) as JsonArrayAttribute;
95 #if !PocketPC && !NET20
96 public static DataContractAttribute GetDataContractAttribute(Type type)
98 return CachedAttributeGetter<DataContractAttribute>.GetAttribute(type);
102 public static MemberSerialization GetObjectMemberSerialization(Type objectType)
104 JsonObjectAttribute objectAttribute = GetJsonObjectAttribute(objectType);
106 if (objectAttribute == null)
108 #if !PocketPC && !NET20
109 DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
111 if (dataContractAttribute != null)
112 return MemberSerialization.OptIn;
115 return MemberSerialization.OptOut;
118 return objectAttribute.MemberSerialization;
121 private static Type GetJsonConverterType(ICustomAttributeProvider attributeProvider)
123 return JsonConverterTypeCache.Get(attributeProvider);
126 private static Type GetJsonConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider)
128 JsonConverterAttribute converterAttribute = GetAttribute<JsonConverterAttribute>(attributeProvider);
129 return (converterAttribute != null)
130 ? converterAttribute.ConverterType
134 public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType)
136 Type converterType = GetJsonConverterType(attributeProvider);
138 if (converterType != null)
140 JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType);
142 if (!memberConverter.CanConvert(targetConvertedType))
143 throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, memberConverter.GetType().Name, attributeProvider, targetConvertedType.Name));
145 return memberConverter;
152 public static TypeConverter GetTypeConverter(Type type)
155 return TypeDescriptor.GetConverter(type);
157 Type converterType = GetTypeConverterType(type);
159 if (converterType != null)
160 return (TypeConverter)ReflectionUtils.CreateInstance(converterType);
167 #if !SILVERLIGHT && !PocketPC && !NET20
168 private static Type GetAssociatedMetadataType(Type type)
170 return AssociatedMetadataTypesCache.Get(type);
173 private static Type GetAssociateMetadataTypeFromAttribute(Type type)
175 Type metadataTypeAttributeType = GetMetadataTypeAttributeType();
176 if (metadataTypeAttributeType == null)
179 object attribute = type.GetCustomAttributes(metadataTypeAttributeType, true).SingleOrDefault();
180 if (attribute == null)
183 IMetadataTypeAttribute metadataTypeAttribute = (DynamicCodeGeneration)
184 ? DynamicWrapper.CreateWrapper<IMetadataTypeAttribute>(attribute)
185 : new LateBoundMetadataTypeAttribute(attribute);
187 return metadataTypeAttribute.MetadataClassType;
190 private static Type GetMetadataTypeAttributeType()
192 // always attempt to get the metadata type attribute type
193 // the assembly may have been loaded since last time
194 if (_cachedMetadataTypeAttributeType == null)
196 Type metadataTypeAttributeType = Type.GetType(MetadataTypeAttributeTypeName);
198 if (metadataTypeAttributeType != null)
199 _cachedMetadataTypeAttributeType = metadataTypeAttributeType;
204 return _cachedMetadataTypeAttributeType;
207 private static T GetAttribute<T>(Type type) where T : Attribute
209 Type metadataType = GetAssociatedMetadataType(type);
210 if (metadataType != null)
212 T attribute = ReflectionUtils.GetAttribute<T>(metadataType, true);
213 if (attribute != null)
217 return ReflectionUtils.GetAttribute<T>(type, true);
220 private static T GetAttribute<T>(MemberInfo memberInfo) where T : Attribute
222 Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType);
223 if (metadataType != null)
225 MemberInfo metadataTypeMemberInfo = metadataType.GetMember(memberInfo.Name,
226 memberInfo.MemberType,
227 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).SingleOrDefault();
229 if (metadataTypeMemberInfo != null)
231 T attribute = ReflectionUtils.GetAttribute<T>(metadataTypeMemberInfo, true);
232 if (attribute != null)
237 return ReflectionUtils.GetAttribute<T>(memberInfo, true);
240 public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute
242 Type type = attributeProvider as Type;
244 return GetAttribute<T>(type);
246 MemberInfo memberInfo = attributeProvider as MemberInfo;
247 if (memberInfo != null)
248 return GetAttribute<T>(memberInfo);
250 return ReflectionUtils.GetAttribute<T>(attributeProvider, true);
253 public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute
255 return ReflectionUtils.GetAttribute<T>(attributeProvider, true);
259 private static bool? _dynamicCodeGeneration;
261 public static bool DynamicCodeGeneration
265 if (_dynamicCodeGeneration == null)
267 #if !PocketPC && !SILVERLIGHT
270 new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
271 new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess).Demand();
272 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
273 _dynamicCodeGeneration = true;
277 _dynamicCodeGeneration = false;
280 _dynamicCodeGeneration = false;
284 return _dynamicCodeGeneration.Value;
288 public static ReflectionDelegateFactory ReflectionDelegateFactory
292 #if !PocketPC && !SILVERLIGHT
293 if (DynamicCodeGeneration)
294 return DynamicReflectionDelegateFactory.Instance;
297 return LateBoundReflectionDelegateFactory.Instance;