public virtual void Write(Enum value) { string enumName = null; Type type = value.GetType(); if (type.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(type, value)) { Enum[] flags = JsonWriter.GetFlagList(type, value); string[] flagNames = new string[flags.Length]; for (int i = 0; i < flags.Length; i++) { flagNames[i] = BTPropertyAttribute.GetPropertyName(flags[i]); if (String.IsNullOrEmpty(flagNames[i])) { flagNames[i] = flags[i].ToString("f"); } } enumName = String.Join(", ", flagNames); } else { enumName = BTPropertyAttribute.GetPropertyName(value); if (String.IsNullOrEmpty(enumName)) { enumName = value.ToString("f"); } } this.Write(enumName); }
/// <summary> /// Gets the name specified for use in serialization. /// </summary> /// <returns></returns> public static string GetPropertyName(object value) { if (value == null) { return(null); } Type type = value.GetType(); MemberInfo memberInfo = null; if (TCU.GetTypeInfo(type).IsEnum) { string name = Enum.GetName(type, value); if (String.IsNullOrEmpty(name)) { return(null); } memberInfo = TCU.GetTypeInfo(type).GetField(name); } else { memberInfo = value as MemberInfo; } if (MemberInfo.Equals(memberInfo, null)) { throw new ArgumentException(); } #if WINDOWS_STORE BTPropertyAttribute attribute = memberInfo.GetCustomAttribute <BTPropertyAttribute>(true); #else BTPropertyAttribute attribute = Attribute.GetCustomAttribute(memberInfo, typeof(BTPropertyAttribute)) as BTPropertyAttribute; #endif return(attribute != null ? attribute.PropertyName : null); }
internal object CoerceType(Type targetType, object value) { bool isNullable = TypeCoercionUtility.IsNullable(targetType); if (value == null) { if (!allowNullValueTypes && TCU.GetTypeInfo(targetType).IsValueType&& !isNullable) { throw new JsonTypeCoercionException(String.Format(TypeCoercionUtility.ErrorNullValueType, new System.Object[] { targetType.FullName })); } return(value); } if (isNullable) { // nullable types have a real underlying struct Type[] genericArgs = targetType.GetGenericArguments(); if (genericArgs.Length == 1) { targetType = genericArgs[0]; } } Type actualType = value.GetType(); if (TCU.GetTypeInfo(targetType).IsAssignableFrom(TCU.GetTypeInfo(actualType))) { return(value); } if (TCU.GetTypeInfo(targetType).IsEnum) { if (value is String) { if (!Enum.IsDefined(targetType, value)) { // if isn't a defined value perhaps it is the JsonName foreach (FieldInfo field in TCU.GetTypeInfo(targetType).GetFields()) { string jsonName = BTPropertyAttribute.GetPropertyName(field); if (((string)value).Equals(jsonName)) { value = field.Name; break; } } } return(Enum.Parse(targetType, (string)value)); } else { value = this.CoerceType(Enum.GetUnderlyingType(targetType), value); return(Enum.ToObject(targetType, value)); } } // Value is of the wrong type and it has been deserialized as an IDictionary. // Previously coercion was supported // but this generally just caused more problems than it solved, so type hints are recommended now. // More specifically this can cause annoying problems with tags when a tag is referencing some object // for which there is no type info for (e.g the field has been removed), that data would have been // deserialized as an IDictionary, but when the tag gets the information it will try to coerce it // which will often fail horribly if (value is IDictionary) { return(null); // Dictionary<string, MemberInfo> memberMap; // return this.CoerceType(targetType, (IDictionary)value, out memberMap); } if (TCU.GetTypeInfo(typeof(IEnumerable)).IsAssignableFrom(TCU.GetTypeInfo(targetType)) && TCU.GetTypeInfo(typeof(IEnumerable)).IsAssignableFrom(TCU.GetTypeInfo(actualType))) { return(this.CoerceList(targetType, actualType, (IEnumerable)value)); } if (value is String) { if (Type.Equals(targetType, typeof(DateTime))) { DateTime date; if (DateTime.TryParse( (string)value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.RoundtripKind | DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault, out date)) { return(date); } } else if (Type.Equals(targetType, typeof(Guid))) { // try-catch is pointless since will throw upon generic conversion return(new Guid((string)value)); } else if (Type.Equals(targetType, typeof(Char))) { if (((string)value).Length == 1) { return(((string)value)[0]); } } else if (Equals(targetType, typeof(Uri))) { Uri uri; if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out uri)) { return(uri); } } else if (Type.Equals(targetType, typeof(Version))) { // try-catch is pointless since will throw upon generic conversion return(new Version((string)value)); } } else if (Type.Equals(targetType, typeof(TimeSpan))) { return(new TimeSpan((long)this.CoerceType(typeof(Int64), value))); } #if !WINPHONE_8 TypeConverter converter = TypeDescriptor.GetConverter(targetType); if (converter.CanConvertFrom(actualType)) { return(converter.ConvertFrom(value)); } converter = TypeDescriptor.GetConverter(actualType); if (converter.CanConvertTo(targetType)) { return(converter.ConvertTo(value, targetType)); } #endif try { // fall back to basics return(Convert.ChangeType(value, targetType)); } catch (Exception ex) { throw new JsonTypeCoercionException( String.Format("Error converting {0} to {1}", new System.Object[] { value.GetType().FullName, targetType.FullName }), ex); } }
/** Creates a member map for the type */ private Dictionary <string, MemberInfo> CreateMemberMap(Type objectType) { Dictionary <string, MemberInfo> memberMap; if (this.MemberMapCache.TryGetValue(objectType, out memberMap)) { // map was stored in cache return(memberMap); } // create a new map memberMap = new Dictionary <string, MemberInfo>(); // load properties into property map Type tp = objectType; while (tp != null) { PropertyInfo[] properties = TCU.GetTypeInfo(tp).GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); for (int i = 0; i < properties.Length; i++) { PropertyInfo info = properties[i]; if (!info.CanRead || !info.CanWrite) { continue; } if (BTIgnoreAttribute.IsJsonIgnore(info)) { continue; } string jsonName = BTPropertyAttribute.GetPropertyName(info); if (String.IsNullOrEmpty(jsonName)) { memberMap[info.Name] = info; } else { memberMap[jsonName] = info; } } // load public fields into property map FieldInfo[] fields = TCU.GetTypeInfo(tp).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo info in fields) { if (!info.IsPublic && #if WINDOWS_STORE info.GetCustomAttribute <JsonMemberAttribute>(false) == null #else info.GetCustomAttributes(typeof(BTPropertyAttribute), false).Length == 0 #endif ) { continue; } if (BTIgnoreAttribute.IsJsonIgnore(info)) { continue; } string jsonName = BTPropertyAttribute.GetPropertyName(info); if (String.IsNullOrEmpty(jsonName)) { memberMap[info.Name] = info; } else { memberMap[jsonName] = info; } } tp = tp.BaseType; } // store in cache for repeated usage this.MemberMapCache[objectType] = memberMap; return(memberMap); }
public void GetMemberWritingMap(Type objectType, JsonWriterSettings settings, out KeyValuePair <string, FieldInfo>[] outFields, out KeyValuePair <string, PropertyInfo>[] outProps) { if (writingMaps == null) { writingMaps = new Dictionary <Type, KeyValuePair <KeyValuePair <string, FieldInfo>[], KeyValuePair <string, PropertyInfo>[]> >(); } KeyValuePair <KeyValuePair <string, FieldInfo>[], KeyValuePair <string, PropertyInfo>[]> pair; if (writingMaps.TryGetValue(objectType, out pair)) { outFields = pair.Key; outProps = pair.Value; return; } bool anonymousType = objectType.IsGenericType && objectType.Name.StartsWith(JsonWriter.AnonymousTypePrefix); Type tp = objectType; if (fieldList == null) { fieldList = new List <KeyValuePair <string, FieldInfo> >(); } if (propList == null) { propList = new List <KeyValuePair <string, PropertyInfo> >(); } fieldList.Clear(); propList.Clear(); while (tp != null) { FieldInfo[] fields = tp.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); for (int j = 0; j < fields.Length; j++) { FieldInfo field = fields[j]; if (field.IsStatic || (!field.IsPublic && field.GetCustomAttributes(typeof(BTPropertyAttribute), true).Length == 0)) { //if (Settings.DebugMode) // Console.WriteLine ("Cannot serialize " + field.Name + " : not public or is static (and does not have a JsonMember attribute)"); continue; } if (settings.IsIgnored(objectType, field, null)) { //if (Settings.DebugMode) // Console.WriteLine ("Cannot serialize " + field.Name + " : ignored by settings"); continue; } // use Attributes here to control naming string fieldName = BTPropertyAttribute.GetPropertyName(field); if (String.IsNullOrEmpty(fieldName)) { fieldName = field.Name; } fieldList.Add(new KeyValuePair <string, FieldInfo>(fieldName, field)); } PropertyInfo[] properties = tp.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); for (int j = 0; j < properties.Length; j++) { PropertyInfo property = properties[j]; //Console.WriteLine (property.Name); if (!property.CanRead) { //if (Settings.DebugMode) // Console.WriteLine ("Cannot serialize "+property.Name+" : cannot read"); continue; } if (!property.CanWrite && !anonymousType) { //if (Settings.DebugMode) // Console.WriteLine ("Cannot serialize "+property.Name+" : cannot write"); continue; } if (settings.IsIgnored(objectType, property, null)) { //if (Settings.DebugMode) // Console.WriteLine ("Cannot serialize "+property.Name+" : is ignored by settings"); continue; } if (property.GetIndexParameters().Length != 0) { //if (Settings.DebugMode) // Console.WriteLine ("Cannot serialize "+property.Name+" : is indexed"); continue; } // use Attributes here to control naming string propertyName = BTPropertyAttribute.GetPropertyName(property); if (String.IsNullOrEmpty(propertyName)) { propertyName = property.Name; } propList.Add(new KeyValuePair <string, PropertyInfo>(propertyName, property)); } tp = tp.BaseType; } outFields = fieldList.ToArray(); outProps = propList.ToArray(); pair = new KeyValuePair <KeyValuePair <string, FieldInfo>[], KeyValuePair <string, PropertyInfo>[]>(outFields, outProps); writingMaps[objectType] = pair; }