public static JsonConverter GetJsonConverter(object attributeProvider) { JsonConverterAttribute converterAttribute = GetCachedAttribute <JsonConverterAttribute>(attributeProvider); if (converterAttribute != null) { Func <object[], JsonConverter> creator = JsonConverterCreatorCache.Get(converterAttribute.ConverterType); if (creator != null) { return(creator(converterAttribute.ConverterParameters)); } } return(null); }
public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType) { Type jsonConverterType = GetJsonConverterType(attributeProvider); if (jsonConverterType != null) { JsonConverter jsonConverter = JsonConverterAttribute.CreateJsonConverterInstance(jsonConverterType); if (!jsonConverter.CanConvert(targetConvertedType)) { throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, jsonConverter.GetType().Name, attributeProvider, targetConvertedType.Name)); } return(jsonConverter); } return(null); }
private static Type GetJsonConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider) { Type converterType; JsonConverterAttribute attribute = JsonTypeReflector.GetAttribute <JsonConverterAttribute>(attributeProvider); if (attribute == null) { converterType = null; } else { converterType = attribute.ConverterType; } return(converterType); }
internal JsonContainerContract(Type underlyingType) : base(underlyingType) { JsonContainerAttribute attribute = Class139.smethod_0(underlyingType); if (attribute != null) { if (attribute.ItemConverterType != null) { this.ItemConverter = JsonConverterAttribute.smethod_0(attribute.ItemConverterType); } this.ItemIsReference = attribute.nullable_1; this.ItemReferenceLoopHandling = attribute.nullable_2; this.ItemTypeNameHandling = attribute.nullable_3; } }
/// <summary> /// Initializes a new instance of the <see cref="JsonContainerContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> internal JsonContainerContract(Type underlyingType) : base(underlyingType) { JsonContainerAttribute jsonContainerAttribute = JsonTypeReflector.GetJsonContainerAttribute(underlyingType); if (jsonContainerAttribute != null) { if (jsonContainerAttribute.ItemConverterType != null) { ItemConverter = JsonConverterAttribute.CreateJsonConverterInstance(jsonContainerAttribute.ItemConverterType); } ItemIsReference = jsonContainerAttribute._itemIsReference; ItemReferenceLoopHandling = jsonContainerAttribute._itemReferenceLoopHandling; ItemTypeNameHandling = jsonContainerAttribute._itemTypeNameHandling; } }
public static JsonConverter GetJsonConverter(object attributeProvider) { JsonConverterAttribute cachedAttribute = JsonTypeReflector.GetCachedAttribute <JsonConverterAttribute>(attributeProvider); if (cachedAttribute != null) { Func <object[], object> func = JsonTypeReflector.CreatorCache.Get(cachedAttribute.ConverterType); if (func != null) { return((JsonConverter)func(cachedAttribute.ConverterParameters)); } } return((JsonConverter)null); }
private void EntityBaseWriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteStartObject(); Type type = value.GetType(); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(type); List <string> fields = null; if (!string.IsNullOrEmpty(Fields)) { fields = new List <string>(); fields.AddRange(Fields.Split(',')); } Type jsonIgnoreAttrType = typeof(JsonIgnoreAttribute); Type jsonConverterAttrType = typeof(JsonConverterAttribute); foreach (PropertyDescriptor prop in properties) { bool canSerializer = true; if (fields != null) { canSerializer = fields.Exists(F => F == prop.Name); } else { JsonIgnoreAttribute jsonIgnore = (JsonIgnoreAttribute)prop.Attributes[jsonIgnoreAttrType]; canSerializer = jsonIgnore == null; } if (canSerializer) { JsonConverter converter = null; JsonConverterAttribute converterAttr = (JsonConverterAttribute)prop.Attributes[jsonConverterAttrType]; if (converterAttr != null) { converter = (JsonConverter)Activator.CreateInstance(converterAttr.ConverterType); serializer.Converters.Add(converter); } writer.WritePropertyName(prop.Name); serializer.Serialize(writer, prop.GetValue(value)); } } writer.WriteEndObject(); }
private static JsonConverter GetConverterFromAttribute(JsonConverterAttribute converterAttribute, Type typeToConvert, MemberInfo?memberInfo, JsonSerializerOptions options) { JsonConverter?converter; Type declaringType = memberInfo?.DeclaringType ?? typeToConvert; Type?converterType = converterAttribute.ConverterType; if (converterType == null) { // Allow the attribute to create the converter. converter = converterAttribute.CreateConverter(typeToConvert); if (converter == null) { ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(declaringType, memberInfo, typeToConvert); } } else { ConstructorInfo?ctor = converterType.GetConstructor(Type.EmptyTypes); if (!typeof(JsonConverter).IsAssignableFrom(converterType) || ctor == null || !ctor.IsPublic) { ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(declaringType, memberInfo); } converter = (JsonConverter)Activator.CreateInstance(converterType) !; } Debug.Assert(converter != null); if (!converter.CanConvert(typeToConvert)) { Type?underlyingType = Nullable.GetUnderlyingType(typeToConvert); if (underlyingType != null && converter.CanConvert(underlyingType)) { if (converter is JsonConverterFactory converterFactory) { converter = converterFactory.GetConverterInternal(underlyingType, options); } // Allow nullable handling to forward to the underlying type's converter. return(NullableConverterFactory.CreateValueConverter(underlyingType, converter)); } ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(declaringType, memberInfo, typeToConvert); } return(converter); }
public void AllEnumsAreMarkedForStringSerialization() { Assembly assembly = Assembly.GetAssembly(typeof(VmState)); IList <Type> enumTypes = assembly.GetTypes().Where(x => x.IsEnum).ToList(); Assert.IsTrue(enumTypes.Count > 0); foreach (Type enumType in enumTypes) { JsonConverterAttribute converterAtrribute = enumType.GetCustomAttribute <JsonConverterAttribute>(); if (converterAtrribute == null) { Assert.Fail($"Attribute not set for {enumType.Name}."); } Assert.AreEqual(typeof(StringEnumConverter), converterAtrribute.ConverterType, $"Wrong converter set for {enumType.Name}."); } }
internal JsonContainerContract(Type underlyingType) : base(underlyingType) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(underlyingType); if (containerAttribute == null) { return; } if (containerAttribute.ItemConverterType != null) { this.ItemConverter = JsonConverterAttribute.CreateJsonConverterInstance(containerAttribute.ItemConverterType); } this.ItemIsReference = containerAttribute._itemIsReference; this.ItemReferenceLoopHandling = containerAttribute._itemReferenceLoopHandling; this.ItemTypeNameHandling = containerAttribute._itemTypeNameHandling; }
private JsonConverter GetConverterFromAttribute(JsonConverterAttribute converterAttribute, Type typeToConvert, Type classTypeAttributeIsOn, PropertyInfo?propertyInfo) { JsonConverter?converter; Type?type = converterAttribute.ConverterType; if (type == null) { // Allow the attribute to create the converter. converter = converterAttribute.CreateConverter(typeToConvert); if (converter == null) { ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(classTypeAttributeIsOn, propertyInfo, typeToConvert); } } else { ConstructorInfo?ctor = type.GetConstructor(Type.EmptyTypes); if (!typeof(JsonConverter).IsAssignableFrom(type) || ctor == null || !ctor.IsPublic) { ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(classTypeAttributeIsOn, propertyInfo); } converter = (JsonConverter)Activator.CreateInstance(type) !; } Debug.Assert(converter != null); if (!converter.CanConvert(typeToConvert)) { Type?underlyingType = Nullable.GetUnderlyingType(typeToConvert); if (underlyingType != null && converter.CanConvert(underlyingType)) { // Allow nullable handling to forward to the underlying type's converter. return(NullableConverterFactory.CreateValueConverter(underlyingType, converter)); } ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(classTypeAttributeIsOn, propertyInfo, typeToConvert); } return(converter); }
public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType) { object provider = null; #if !(NETFX_CORE || PORTABLE) provider = attributeProvider as MemberInfo; #else provider = attributeProvider.UnderlyingObject; #endif Type converterType = GetJsonConverterType(attributeProvider); if (converterType != null) { JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType); return(memberConverter); } return(null); }
/*internal static SqlRelationshipLookup GetPropertyRelationshipLookup(PropertyInfo prop) * { * var attributes = prop.GetCustomAttributes(true); * if (attributes.Length > 0) * { * foreach (var attribute in attributes) * { * if (attribute.GetType().Name == "SqlRelationshipLookup") * { * return attribute as SqlRelationshipLookup; * } * } * } * return null; * }*/ private static void SetCsvConversion(PropertyInfo prop, object obj, object value) { var attributes = prop.GetCustomAttributes(true); if (attributes.Length > 0) { foreach (var attribute in attributes) { if (attribute.GetType().Name == "JsonConverterAttribute") { JsonConverterAttribute converter = attribute as JsonConverterAttribute; if (converter.ConverterType.Name == "CsvConverter") { prop.SetValue(obj, new List <string>(value.ToString().Split(','))); return; } } } } prop.SetValue(obj, value); }
internal JsonConverter DetermineConverterForProperty(Type parentClassType, Type runtimePropertyType, PropertyInfo propertyInfo) { JsonConverter converter = null; // Priority 1: attempt to get converter from JsonConverterAttribute on property. if (propertyInfo != null) { JsonConverterAttribute converterAttribute = (JsonConverterAttribute) GetAttributeThatCanHaveMultiple(parentClassType, typeof(JsonConverterAttribute), propertyInfo); if (converterAttribute != null) { converter = GetConverterFromAttribute(converterAttribute, runtimePropertyType, parentClassType, propertyInfo); } } if (converter == null) { converter = GetConverter(runtimePropertyType); } return(converter); }
private static object GetCsvConversion(PropertyInfo prop, object obj) { var attributes = prop.GetCustomAttributes(true); if (attributes.Length > 0) { foreach (var attribute in attributes) { if (attribute.GetType().Name == "JsonConverterAttribute") { JsonConverterAttribute converter = attribute as JsonConverterAttribute; if (converter.ConverterType.Name == "CsvConverter") { CsvConverter csv = new CsvConverter(); JsonStringWriter jWrite = new JsonStringWriter(); csv.WriteJson(jWrite, prop.GetValue(obj), new JsonSerializer()); return(jWrite.Output); } } } } return(prop.GetValue(obj)); }
public static List <KeyValuePair <string, object> > PrepareFormFieldsFromObject( string name, object value, List <KeyValuePair <string, object> > keys = null, PropertyInfo propInfo = null, ArrayDeserialization arrayDeserializationFormat = ArrayDeserialization.UnIndexed) { keys = keys ?? new List <KeyValuePair <string, object> >(); if (value == null) { return(keys); } else if (value is Stream) { keys.Add(new KeyValuePair <string, object>(name, value)); return(keys); } else if (value is JObject) { var valueAccept = (value as JObject); foreach (var property in valueAccept.Properties()) { string pKey = property.Name; object pValue = property.Value; var fullSubName = name + '[' + pKey + ']'; PrepareFormFieldsFromObject(fullSubName, pValue, keys, propInfo, arrayDeserializationFormat); } } else if (value is IList) { var enumerator = ((IEnumerable)value).GetEnumerator(); var hasNested = false; while (enumerator.MoveNext()) { var subValue = enumerator.Current; if (subValue != null && (subValue is JObject || subValue is IList || subValue is IDictionary || !(subValue.GetType().Namespace.StartsWith("System")))) { hasNested = true; break; } } int i = 0; enumerator.Reset(); while (enumerator.MoveNext()) { var fullSubName = name + '[' + i + ']'; if (!hasNested && arrayDeserializationFormat == ArrayDeserialization.UnIndexed) { fullSubName = name + "[]"; } else if (!hasNested && arrayDeserializationFormat == ArrayDeserialization.Plain) { fullSubName = name; } var subValue = enumerator.Current; if (subValue == null) { continue; } PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo, arrayDeserializationFormat); i++; } } else if (value is JToken) { keys.Add(new KeyValuePair <string, object>(name, value.ToString())); } else if (value is Enum) { #if WINDOWS_UWP || NETSTANDARD1_3 Assembly thisAssembly = typeof(APIHelper).GetTypeInfo().Assembly; #else Assembly thisAssembly = Assembly.GetExecutingAssembly(); #endif string enumTypeName = value.GetType().FullName; Type enumHelperType = thisAssembly.GetType(string.Format("{0}Helper", enumTypeName)); object enumValue = (int)value; if (enumHelperType != null) { //this enum has an associated helper, use that to load the value #if NETSTANDARD1_3 MethodInfo enumHelperMethod = enumHelperType.GetRuntimeMethod("ToValue", new[] { value.GetType() }); #else MethodInfo enumHelperMethod = enumHelperType.GetMethod("ToValue", new[] { value.GetType() }); #endif if (enumHelperMethod != null) { enumValue = enumHelperMethod.Invoke(null, new object[] { value }); } } keys.Add(new KeyValuePair <string, object>(name, enumValue)); } else if (value is IDictionary) { var obj = (IDictionary)value; foreach (var sName in obj.Keys) { var subName = sName.ToString(); var subValue = obj[subName]; string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']'; PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo, arrayDeserializationFormat); } } else if (!(value.GetType().Namespace.StartsWith("System"))) { //Custom object Iterate through its properties #if NETSTANDARD1_3 var enumerator = value.GetType().GetRuntimeProperties().GetEnumerator(); #else var enumerator = value.GetType().GetProperties().GetEnumerator();; #endif PropertyInfo pInfo = null; var t = new JsonPropertyAttribute().GetType(); while (enumerator.MoveNext()) { pInfo = enumerator.Current as PropertyInfo; var jsonProperty = (JsonPropertyAttribute)pInfo.GetCustomAttributes(t, true).FirstOrDefault(); var subName = (jsonProperty != null) ? jsonProperty.PropertyName : pInfo.Name; string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']'; var subValue = pInfo.GetValue(value, null); PrepareFormFieldsFromObject(fullSubName, subValue, keys, pInfo, arrayDeserializationFormat); } } else if (value is DateTime) { string convertedValue = null; #if NETSTANDARD1_3 IEnumerable <Attribute> pInfo = null; #else object[] pInfo = null; #endif if (propInfo != null) { pInfo = propInfo.GetCustomAttributes(true); } if (pInfo != null) { foreach (object attr in pInfo) { JsonConverterAttribute converterAttr = attr as JsonConverterAttribute; if (converterAttr != null) { convertedValue = JsonSerialize(value, (JsonConverter) Activator.CreateInstance(converterAttr.ConverterType, converterAttr.ConverterParameters)).Replace("\"", ""); } } } keys.Add(new KeyValuePair <string, object>(name, (convertedValue) ?? ((DateTime)value).ToString(DateTimeFormat))); } else { keys.Add(new KeyValuePair <string, object>(name, value)); } return(keys); }
private void method_11(JsonProperty jsonProperty_0, object object_1, string string_0, Type type_0, MemberSerialization memberSerialization_0, out bool bool_4) { DataMemberAttribute attribute2; string propertyName; DataContractAttribute attribute = Class139.smethod_5(type_0); MemberInfo info = object_1 as MemberInfo; if ((attribute != null) && (info != null)) { attribute2 = Class139.smethod_6(info); } else { attribute2 = null; } JsonPropertyAttribute attribute3 = Class139.smethod_17 <JsonPropertyAttribute>(object_1); if (attribute3 != null) { jsonProperty_0.HasMemberAttribute = true; } if ((attribute3 != null) && (attribute3.PropertyName != null)) { propertyName = attribute3.PropertyName; } else if ((attribute2 != null) && (attribute2.Name != null)) { propertyName = attribute2.Name; } else { propertyName = string_0; } jsonProperty_0.PropertyName = this.ResolvePropertyName(propertyName); jsonProperty_0.UnderlyingName = string_0; bool flag = false; if (attribute3 != null) { jsonProperty_0.nullable_0 = attribute3.nullable_7; jsonProperty_0.Order = attribute3.nullable_6; jsonProperty_0.DefaultValueHandling = attribute3.nullable_1; flag = true; } else if (attribute2 != null) { jsonProperty_0.nullable_0 = new Required?(attribute2.IsRequired ? Required.AllowNull : Required.Default); jsonProperty_0.Order = (attribute2.Order != -1) ? new int?(attribute2.Order) : null; jsonProperty_0.DefaultValueHandling = !attribute2.EmitDefaultValue ? ((DefaultValueHandling?)1) : null; flag = true; } bool flag2 = ((Class139.smethod_17 <JsonIgnoreAttribute>(object_1) != null) || (Class139.smethod_17 <JsonExtensionDataAttribute>(object_1) != null)) || (Class139.smethod_17 <NonSerializedAttribute>(object_1) != null); if (memberSerialization_0 != MemberSerialization.OptIn) { bool flag3 = false; flag3 = Class139.smethod_17 <IgnoreDataMemberAttribute>(object_1) != null; jsonProperty_0.Ignored = flag2 || flag3; } else { jsonProperty_0.Ignored = flag2 || !flag; } jsonProperty_0.Converter = Class139.smethod_10(object_1, jsonProperty_0.PropertyType); jsonProperty_0.MemberConverter = Class139.smethod_10(object_1, jsonProperty_0.PropertyType); DefaultValueAttribute attribute4 = Class139.smethod_17 <DefaultValueAttribute>(object_1); if (attribute4 != null) { jsonProperty_0.DefaultValue = attribute4.Value; } jsonProperty_0.NullValueHandling = (attribute3 != null) ? attribute3.nullable_0 : null; jsonProperty_0.ReferenceLoopHandling = (attribute3 != null) ? attribute3.nullable_2 : null; jsonProperty_0.ObjectCreationHandling = (attribute3 != null) ? attribute3.nullable_3 : null; jsonProperty_0.TypeNameHandling = (attribute3 != null) ? attribute3.nullable_4 : null; jsonProperty_0.IsReference = (attribute3 != null) ? attribute3.nullable_5 : null; jsonProperty_0.ItemIsReference = (attribute3 != null) ? attribute3.nullable_8 : null; jsonProperty_0.ItemConverter = ((attribute3 == null) || (attribute3.ItemConverterType == null)) ? null : JsonConverterAttribute.smethod_0(attribute3.ItemConverterType); jsonProperty_0.ItemReferenceLoopHandling = (attribute3 != null) ? attribute3.nullable_9 : null; jsonProperty_0.ItemTypeNameHandling = (attribute3 != null) ? attribute3.nullable_10 : null; bool_4 = false; if ((this.DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic) { bool_4 = true; } if (attribute3 != null) { bool_4 = true; } if (memberSerialization_0 == MemberSerialization.Fields) { bool_4 = true; } if (attribute2 != null) { bool_4 = true; jsonProperty_0.HasMemberAttribute = true; } }
private void SetPropertySettingsFromAttributes(JsonProperty property, ICustomAttributeProvider attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess, out bool hasExplicitAttribute) { hasExplicitAttribute = false; #if !PocketPC && !NET20 DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType); MemberInfo memberInfo = null; #if !(NETFX_CORE || PORTABLE) memberInfo = attributeProvider as MemberInfo; #else memberInfo = attributeProvider.UnderlyingObject as MemberInfo; #endif DataMemberAttribute dataMemberAttribute; if (dataContractAttribute != null && memberInfo != null) { dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)memberInfo); } else { dataMemberAttribute = null; } #endif JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(attributeProvider); if (propertyAttribute != null) { hasExplicitAttribute = true; } string mappedName; if (propertyAttribute != null && propertyAttribute.PropertyName != null) { mappedName = propertyAttribute.PropertyName; } #if !PocketPC && !NET20 else if (dataMemberAttribute != null && dataMemberAttribute.Name != null) { mappedName = dataMemberAttribute.Name; } #endif else { mappedName = name; } property.PropertyName = ResolvePropertyName(mappedName); property.UnderlyingName = name; if (propertyAttribute != null) { property._required = propertyAttribute._required; property.Order = propertyAttribute._order; } #if !PocketPC && !NET20 else if (dataMemberAttribute != null) { property._required = (dataMemberAttribute.IsRequired) ? Required.AllowNull : Required.Default; property.Order = (dataMemberAttribute.Order != -1) ? (int?)dataMemberAttribute.Order : null; } #endif bool hasJsonIgnoreAttribute = JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(attributeProvider) != null #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) || JsonTypeReflector.GetAttribute <NonSerializedAttribute>(attributeProvider) != null #endif ; if (memberSerialization != MemberSerialization.OptIn) { // ignored if it has JsonIgnore or NonSerialized attributes property.Ignored = hasJsonIgnoreAttribute; } else { // ignored if it has JsonIgnore/NonSerialized or does not have DataMember or JsonProperty attributes property.Ignored = hasJsonIgnoreAttribute || (propertyAttribute == null #if !PocketPC && !NET20 && dataMemberAttribute == null #endif ); } // resolve converter for property // the class type might have a converter but the property converter takes presidence property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType); property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType); DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(attributeProvider); property.DefaultValue = (defaultValueAttribute != null) ? defaultValueAttribute.Value : null; property.NullValueHandling = (propertyAttribute != null) ? propertyAttribute._nullValueHandling : null; property.DefaultValueHandling = (propertyAttribute != null) ? propertyAttribute._defaultValueHandling : null; property.ReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._referenceLoopHandling : null; property.ObjectCreationHandling = (propertyAttribute != null) ? propertyAttribute._objectCreationHandling : null; property.TypeNameHandling = (propertyAttribute != null) ? propertyAttribute._typeNameHandling : null; property.IsReference = (propertyAttribute != null) ? propertyAttribute._isReference : null; property.ItemIsReference = (propertyAttribute != null) ? propertyAttribute._itemIsReference : null; property.ItemConverter = (propertyAttribute != null && propertyAttribute.ItemConverterType != null) ? JsonConverterAttribute.CreateJsonConverterInstance(propertyAttribute.ItemConverterType) : null; property.ItemReferenceLoopHandling = (propertyAttribute != null) ? propertyAttribute._itemReferenceLoopHandling : null; property.ItemTypeNameHandling = (propertyAttribute != null) ? propertyAttribute._itemTypeNameHandling : null; allowNonPublicAccess = false; if ((DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic) { allowNonPublicAccess = true; } if (propertyAttribute != null) { allowNonPublicAccess = true; } if (memberSerialization == MemberSerialization.Fields) { allowNonPublicAccess = true; } #if !PocketPC && !NET20 if (dataMemberAttribute != null) { allowNonPublicAccess = true; hasExplicitAttribute = true; } #endif }
internal static void GetJsonAttributeAndPathsByMemberInfo(MemberInfo memberInfo, out JsonPropertyAttribute propAtt, out JsonPathAttribute pathAtt, out JsonConverterAttribute convAtt, out List <string> jsonPaths) { propAtt = null; pathAtt = null; convAtt = null; jsonPaths = new List <string>(); foreach (object customAttribute in memberInfo.GetCustomAttributes(true)) { if (customAttribute.GetType() == typeof(JsonPropertyAttribute)) { propAtt = customAttribute as JsonPropertyAttribute; } else if (customAttribute.GetType() == typeof(JsonPathAttribute)) { pathAtt = customAttribute as JsonPathAttribute; } else if (customAttribute.GetType() == typeof(JsonConverterAttribute)) { convAtt = customAttribute as JsonConverterAttribute; } } #region Récupération des Path par priorité : JsonPath / JsonProperty / PropertyName if (propAtt != null && !String.IsNullOrEmpty(propAtt.PropertyName)) { jsonPaths.Add(propAtt.PropertyName); } if (pathAtt != null) { foreach (string path in pathAtt.JPaths) { jsonPaths.Add(path); } } jsonPaths.Add(memberInfo.Name); #endregion }
/// <summary> /// Prepares the object as form fields using the provided name. /// </summary> /// <param name="name">root name for the variable</param> /// <param name="value">form field value</param> /// <param name="keys">Contains a flattend and form friendly values</param> /// <returns>Contains a flattend and form friendly values</returns> public static Dictionary <string, object> PrepareFormFieldsFromObject( string name, object value, Dictionary <string, object> keys = null, PropertyInfo propInfo = null) { keys = keys ?? new Dictionary <string, object>(); if (value == null) { return(keys); } else if (value is Stream) { keys[name] = value; return(keys); } else if (value is JObject) { var valueAccept = (value as Newtonsoft.Json.Linq.JObject); foreach (var property in valueAccept.Properties()) { string pKey = property.Name; object pValue = property.Value; var fullSubName = name + '[' + pKey + ']'; PrepareFormFieldsFromObject(fullSubName, pValue, keys, propInfo); } } else if (value is IList) { int i = 0; var enumerator = ((IEnumerable)value).GetEnumerator(); while (enumerator.MoveNext()) { var subValue = enumerator.Current; if (subValue == null) { continue; } var fullSubName = name + '[' + i + ']'; PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo); i++; } } else if (value is JToken) { keys[name] = value.ToString(); } else if (value is Enum) { #if WINDOWS_UWP Assembly thisAssembly = typeof(APIHelper).GetTypeInfo().Assembly; #else Assembly thisAssembly = Assembly.GetExecutingAssembly(); #endif string enumTypeName = value.GetType().FullName; Type enumHelperType = thisAssembly.GetType(string.Format("{0}Helper", enumTypeName)); object enumValue = (int)value; if (enumHelperType != null) { //this enum has an associated helper, use that to load the value MethodInfo enumHelperMethod = enumHelperType.GetMethod("ToValue", new[] { value.GetType() }); if (enumHelperMethod != null) { enumValue = enumHelperMethod.Invoke(null, new object[] { value }); } } keys[name] = enumValue; } else if (value is IDictionary) { var obj = (IDictionary)value; foreach (var sName in obj.Keys) { var subName = sName.ToString(); var subValue = obj[subName]; string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']'; PrepareFormFieldsFromObject(fullSubName, subValue, keys, propInfo); } } else if (!(value.GetType().Namespace.StartsWith("System"))) { //Custom object Iterate through its properties var enumerator = value.GetType().GetProperties().GetEnumerator(); PropertyInfo pInfo = null; var t = new JsonPropertyAttribute().GetType(); while (enumerator.MoveNext()) { pInfo = enumerator.Current as PropertyInfo; var jsonProperty = (JsonPropertyAttribute)pInfo.GetCustomAttributes(t, true).FirstOrDefault(); var subName = (jsonProperty != null) ? jsonProperty.PropertyName : pInfo.Name; string fullSubName = string.IsNullOrWhiteSpace(name) ? subName : name + '[' + subName + ']'; var subValue = pInfo.GetValue(value, null); PrepareFormFieldsFromObject(fullSubName, subValue, keys, pInfo); } } else if (value is DateTime) { string convertedValue = null; var pInfo = propInfo?.GetCustomAttributes(true); if (pInfo != null) { foreach (object attr in pInfo) { JsonConverterAttribute converterAttr = attr as JsonConverterAttribute; if (converterAttr != null) { convertedValue = JsonSerialize(value, (JsonConverter)Activator.CreateInstance(converterAttr.ConverterType, converterAttr.ConverterParameters)).Replace("\"", ""); } } } keys[name] = (convertedValue) ?? ((DateTime)value).ToString(DateTimeFormat); } else { keys[name] = value; } return(keys); }
/// <summary> /// Returns the converter for the specified type. /// </summary> /// <param name="typeToConvert">The type to return a converter for.</param> /// <returns> /// The first converter that supports the given type, or null if there is no converter. /// </returns> public JsonConverter GetConverter(Type typeToConvert) { if (_converters.TryGetValue(typeToConvert, out JsonConverter converter)) { return(converter); } // Priority 2: Attempt to get custom converter added at runtime. // Currently there is not a way at runtime to overide the [JsonConverter] when applied to a property. foreach (JsonConverter item in Converters) { if (item.CanConvert(typeToConvert)) { converter = item; break; } } // Priority 3: Attempt to get converter from [JsonConverter] on the type being converted. if (converter == null) { JsonConverterAttribute converterAttribute = (JsonConverterAttribute) GetAttributeThatCanHaveMultiple(typeToConvert, typeof(JsonConverterAttribute)); if (converterAttribute != null) { converter = GetConverterFromAttribute(converterAttribute, typeToConvert: typeToConvert, classTypeAttributeIsOn: typeToConvert, propertyInfo: null); } } // Priority 4: Attempt to get built-in converter. if (converter == null) { if (s_defaultSimpleConverters.TryGetValue(typeToConvert, out JsonConverter foundConverter)) { converter = foundConverter; } else { foreach (JsonConverter item in s_defaultFactoryConverters) { if (item.CanConvert(typeToConvert)) { converter = item; break; } } } } // Allow redirection for generic types or the enum converter. if (converter is JsonConverterFactory factory) { converter = factory.GetConverterInternal(typeToConvert, this); if (converter == null || converter.TypeToConvert == null) { throw new ArgumentNullException("typeToConvert"); } } if (converter != null) { Type converterTypeToConvert = converter.TypeToConvert; if (!converterTypeToConvert.IsAssignableFrom(typeToConvert) && !typeToConvert.IsAssignableFrom(converterTypeToConvert)) { ThrowHelper.ThrowInvalidOperationException_SerializationConverterNotCompatible(converter.GetType(), typeToConvert); } } // Only cache the value once (de)serialization has occurred since new converters can be added that may change the result. if (_haveTypesBeenCreated) { // A null converter is allowed here and cached. // Ignore failure case here in multi-threaded cases since the cached item will be equivalent. _converters.TryAdd(typeToConvert, converter); } return(converter); }
private void SetPropertySettingsFromAttributes(JsonProperty property, object attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess) { DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType); MemberInfo memberInfo = attributeProvider as MemberInfo; DataMemberAttribute dataMemberAttribute; if (dataContractAttribute != null && memberInfo != null) { dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute(memberInfo); } else { dataMemberAttribute = null; } JsonPropertyAttribute attribute = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(attributeProvider); if (attribute != null) { property.HasMemberAttribute = true; } string propertyName; if (attribute != null && attribute.PropertyName != null) { propertyName = attribute.PropertyName; } else if (dataMemberAttribute != null && dataMemberAttribute.Name != null) { propertyName = dataMemberAttribute.Name; } else { propertyName = name; } property.PropertyName = this.ResolvePropertyName(propertyName); property.UnderlyingName = name; bool flag = false; if (attribute != null) { property._required = attribute._required; property.Order = attribute._order; property.DefaultValueHandling = attribute._defaultValueHandling; flag = true; } else if (dataMemberAttribute != null) { property._required = new Required?(dataMemberAttribute.IsRequired ? Required.AllowNull : Required.Default); property.Order = ((dataMemberAttribute.Order != -1) ? new int?(dataMemberAttribute.Order) : null); property.DefaultValueHandling = ((!dataMemberAttribute.EmitDefaultValue) ? new DefaultValueHandling?(DefaultValueHandling.Ignore) : null); flag = true; } bool flag2 = JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(attributeProvider) != null || JsonTypeReflector.GetAttribute <JsonExtensionDataAttribute>(attributeProvider) != null || JsonTypeReflector.GetAttribute <NonSerializedAttribute>(attributeProvider) != null; if (memberSerialization != MemberSerialization.OptIn) { bool flag3 = JsonTypeReflector.GetAttribute <IgnoreDataMemberAttribute>(attributeProvider) != null; property.Ignored = (flag2 || flag3); } else { property.Ignored = (flag2 || !flag); } property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType); property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType); DefaultValueAttribute attribute2 = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(attributeProvider); if (attribute2 != null) { property.DefaultValue = attribute2.Value; } property.NullValueHandling = ((attribute != null) ? attribute._nullValueHandling : null); property.ReferenceLoopHandling = ((attribute != null) ? attribute._referenceLoopHandling : null); property.ObjectCreationHandling = ((attribute != null) ? attribute._objectCreationHandling : null); property.TypeNameHandling = ((attribute != null) ? attribute._typeNameHandling : null); property.IsReference = ((attribute != null) ? attribute._isReference : null); property.ItemIsReference = ((attribute != null) ? attribute._itemIsReference : null); property.ItemConverter = ((attribute != null && attribute.ItemConverterType != null) ? JsonConverterAttribute.CreateJsonConverterInstance(attribute.ItemConverterType) : null); property.ItemReferenceLoopHandling = ((attribute != null) ? attribute._itemReferenceLoopHandling : null); property.ItemTypeNameHandling = ((attribute != null) ? attribute._itemTypeNameHandling : null); allowNonPublicAccess = false; if ((this.DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic) { allowNonPublicAccess = true; } if (attribute != null) { allowNonPublicAccess = true; } if (memberSerialization == MemberSerialization.Fields) { allowNonPublicAccess = true; } if (dataMemberAttribute != null) { allowNonPublicAccess = true; property.HasMemberAttribute = true; } }
private void SetPropertySettingsFromAttributes(JsonProperty property, ICustomAttributeProvider attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess) { JsonPropertyAttribute attribute1 = JsonTypeReflector.GetAttribute <JsonPropertyAttribute>(attributeProvider); if (attribute1 != null) { property.HasMemberAttribute = true; } string propertyName = attribute1 == null || attribute1.PropertyName == null ? name : attribute1.PropertyName; property.PropertyName = this.ResolvePropertyName(propertyName); property.UnderlyingName = name; bool flag1 = false; if (attribute1 != null) { property._required = attribute1._required; property.Order = attribute1._order; property.DefaultValueHandling = attribute1._defaultValueHandling; flag1 = true; } bool flag2 = JsonTypeReflector.GetAttribute <JsonIgnoreAttribute>(attributeProvider) != null || JsonTypeReflector.GetAttribute <NonSerializedAttribute>(attributeProvider) != null; if (memberSerialization != MemberSerialization.OptIn) { bool flag3 = false; property.Ignored = flag2 || flag3; } else { property.Ignored = flag2 || !flag1; } property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType); property.MemberConverter = JsonTypeReflector.GetJsonConverter(attributeProvider, property.PropertyType); DefaultValueAttribute attribute2 = JsonTypeReflector.GetAttribute <DefaultValueAttribute>(attributeProvider); if (attribute2 != null) { property.DefaultValue = attribute2.Value; } property.NullValueHandling = attribute1 != null ? attribute1._nullValueHandling : new NullValueHandling?(); property.ReferenceLoopHandling = attribute1 != null ? attribute1._referenceLoopHandling : new ReferenceLoopHandling?(); property.ObjectCreationHandling = attribute1 != null ? attribute1._objectCreationHandling : new ObjectCreationHandling?(); property.TypeNameHandling = attribute1 != null ? attribute1._typeNameHandling : new TypeNameHandling?(); property.IsReference = attribute1 != null ? attribute1._isReference : new bool?(); property.ItemIsReference = attribute1 != null ? attribute1._itemIsReference : new bool?(); property.ItemConverter = attribute1 == null || attribute1.ItemConverterType == null ? (JsonConverter)null : JsonConverterAttribute.CreateJsonConverterInstance(attribute1.ItemConverterType); property.ItemReferenceLoopHandling = attribute1 != null ? attribute1._itemReferenceLoopHandling : new ReferenceLoopHandling?(); property.ItemTypeNameHandling = attribute1 != null ? attribute1._itemTypeNameHandling : new TypeNameHandling?(); allowNonPublicAccess = false; if ((this.DefaultMembersSearchFlags & BindingFlags.NonPublic) == BindingFlags.NonPublic) { allowNonPublicAccess = true; } if (attribute1 != null) { allowNonPublicAccess = true; } if (memberSerialization != MemberSerialization.Fields) { return; } allowNonPublicAccess = true; }
/// <summary> /// Méthode de lecture du Json /// </summary> /// <param name="reader"></param> /// <param name="objectType"></param> /// <param name="existingValue"></param> /// <param name="serializer"></param> /// <returns></returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jo = JObject.Load(reader); object targetObj = Activator.CreateInstance(objectType); foreach (PropertyInfo prop in objectType.GetProperties()) { if (prop.CanRead && prop.CanWrite) { JsonPropertyAttribute propAtt = null; JsonPathAttribute pathAtt = null; JsonConverterAttribute convAtt = null; List <string> jsonPaths = null; ToolsJsonNet.GetJsonAttributeAndPathsByMemberInfo(prop, out propAtt, out pathAtt, out convAtt, out jsonPaths); #region Application du Converter JsonConverter conv = null; if (serializer != null && convAtt != null) { conv = (JsonConverter)Activator.CreateInstance(convAtt.ConverterType); serializer.Converters.Add(conv); } #endregion JToken token = null; foreach (string jsonPath in jsonPaths) { token = jo.SelectToken(jsonPath); // On exploite le 1er path qui match avec notre Json if (token != null) { break; } } if (token != null && token.Type != JTokenType.Null) { // Si le token est un noeud final de l'arbre, qu'il n'est pas une chaîne de caractére et que le noeud Json ne posséde pas de valeur if (token is JValue && prop.PropertyType != typeof(string) && ((JValue)token).Value is string && ((string)((JValue)token).Value) == string.Empty) { // On assigne la valeur par default du Type (cela évite des probléme de cast avec les int et autre type) prop.SetValue(targetObj, ToolsType.GetDefault(prop.PropertyType), null); } else { object value = token.ToObject(prop.PropertyType, serializer); prop.SetValue(targetObj, value, null); } } } } foreach (FieldInfo field in objectType.GetFields()) { JsonPropertyAttribute propAtt = null; JsonPathAttribute pathAtt = null; JsonConverterAttribute convAtt = null; List <string> jsonPaths = null; ToolsJsonNet.GetJsonAttributeAndPathsByMemberInfo(field, out propAtt, out pathAtt, out convAtt, out jsonPaths); #region Application du Converter JsonConverter conv = null; if (serializer != null && convAtt != null) { conv = (JsonConverter)Activator.CreateInstance(convAtt.ConverterType); serializer.Converters.Add(conv); } #endregion JToken token = null; foreach (string jsonPath in jsonPaths) { token = jo.SelectToken(jsonPath); // On exploite le 1er path qui match avec notre Json if (token != null) { break; } } if (token != null && token.Type != JTokenType.Null) { // Si le token est un noeud final de l'arbre, qu'il n'est pas une chaîne de caractére et que le noeud Json ne posséde pas de valeur if (token is JValue && field.FieldType != typeof(string) && ((JValue)token).Value is string && ((string)((JValue)token).Value) == string.Empty) { // On assigne la valeur par default du Type (cela évite des probléme de cast avec les int et autre type) field.SetValue(targetObj, ToolsType.GetDefault(field.FieldType)); } else { object value = token.ToObject(field.FieldType, serializer); field.SetValue(targetObj, value); } } } return(targetObj); }
private static Type GetJsonConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider) { JsonConverterAttribute attribute = JsonTypeReflector.GetAttribute <JsonConverterAttribute>(attributeProvider); return((attribute == null) ? null : attribute.ConverterType); }
private static T Populate <T>(Newtonsoft.Json.Linq.JToken jsonToken, T target, JsonSerializer serializer) { // Si on exploite "target" sous sa forme typée alors le SetValue n'impacte pas l'instance de notre objet object targetObject = (object)target; Type targetType = target.GetType(); Dictionary <List <string>, MemberInfo> lstMembers = new Dictionary <List <string>, MemberInfo>(); List <MemberInfo> memberInfosAtCheck = new List <MemberInfo>(); memberInfosAtCheck.AddRange(targetType.GetProperties()); memberInfosAtCheck.AddRange(targetType.GetFields()); foreach (MemberInfo memberInfo in memberInfosAtCheck) { JsonPropertyAttribute propAtt = null; JsonConverterAttribute convAtt = null; JsonPathAttribute pathAtt = null; List <string> jsonPaths = null; ToolsJsonNet.GetJsonAttributeAndPathsByMemberInfo(memberInfo, out propAtt, out pathAtt, out convAtt, out jsonPaths); #region Application du Converter JsonConverter conv = null; if (serializer != null && convAtt != null) { conv = (JsonConverter)Activator.CreateInstance(convAtt.ConverterType); serializer.Converters.Add(conv); } #endregion lstMembers.Add(jsonPaths, memberInfo); } foreach (List <string> memberPaths in lstMembers.Keys) { JToken jToken = null; foreach (string memberPath in memberPaths) { IEnumerator <JToken> jTokens = jsonToken.SelectTokens(memberPath).GetEnumerator(); // Récupération du 1er element de la liste (si existant) if (jTokens.MoveNext()) { jToken = jTokens.Current; } // On exploite le 1er path qui match avec notre Json if (jToken != null) { break; } } if (jToken != null && jToken.Type != JTokenType.Null) { if (lstMembers[memberPaths] is PropertyInfo) { PropertyInfo propertyInfo = (PropertyInfo)lstMembers[memberPaths]; object value = ExtractValue(serializer, jToken, propertyInfo.PropertyType); propertyInfo.SetValue(targetObject, value, null); } else { FieldInfo fieldInfo = (FieldInfo)lstMembers[memberPaths]; object value = ExtractValue(serializer, jToken, fieldInfo.FieldType); fieldInfo.SetValue(targetObject, value); } } } return((T)targetObject); }
/// <inheritdoc /> public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { JsonConverterAttribute attribute = typeToConvert.GetCustomAttribute <JsonConverterAttribute>() !; return((Activator.CreateInstance(attribute.ConverterType) as JsonConverter) !); }
private void WriteJsonProperty(JsonWriter writer, string propertyName, object propertyValue, JsonSerializer serializer, JsonConverterAttribute propertyConverterAttribute) { writer.WritePropertyName(propertyName); if (propertyConverterAttribute != null) { var converter = (JsonConverter)Activator.CreateInstance(propertyConverterAttribute.ConverterType); var propertyJsonSerializer = new JsonSerializer(); propertyJsonSerializer.Converters.Add(converter); propertyJsonSerializer.Serialize(writer, propertyValue); } else { serializer.Serialize(writer, propertyValue); } }