public virtual void SetDerializedProperty(object obj, PropertyInfo property, IDictionary <string, object> dictionary, JavaScriptSerializer serializer) { if (obj == null || property == null || !property.CanWrite || dictionary == null || serializer == null) { return; } JsonNameAttribute jsonPropertyAttribute = GetJsonPropertyAttribute(property); if (jsonPropertyAttribute == null || jsonPropertyAttribute.Ignored) { return; } string name = jsonPropertyAttribute.PropertyName; if (!dictionary.ContainsKey(name)) { return; } object value = dictionary[name]; // Important! Use JavaScriptSerializer.ConvertToType so that V3JsonConvert of properties of this class are called recursively. object convertedValue = serializer.ConvertToType(value, property.PropertyType); property.SetValue(obj, convertedValue); }
protected virtual KeyValuePair <string, object> GetSerializedProperty(object obj, PropertyInfo property) { var result = new KeyValuePair <string, object>(); if (property == null || !property.CanRead) { return(result); } object value = property.GetValue(obj); JsonClassAttribute jsonClassAttribute = GetJsonClassAttribute(obj); bool ignoreNull = true; if (jsonClassAttribute != null) { ignoreNull = !jsonClassAttribute.SerializeNullValues; } if (value == null && ignoreNull) { return(result); } JsonNameAttribute jsonPropertyAttribute = GetJsonPropertyAttribute(property); if (jsonPropertyAttribute == null || jsonPropertyAttribute.Ignored) { return(result); } bool ignoreDefault = true; if (jsonClassAttribute != null) { ignoreDefault = !jsonClassAttribute.SerializeDefaultValues; } if (IsNullOrDefault(value) && ignoreDefault) { return(result); } if (property.PropertyType == typeof(DateTime)) { value = ((DateTime)value).ToString("G", DateTimeFormatInfo.InvariantInfo); } string name = jsonPropertyAttribute.PropertyName; return(new KeyValuePair <string, object>(name, value)); }
/// <summary> /// Get the Property Attribute e.g. [JsonProperty(PropertyName = "Udf/$TYPEID(252)")] /// </summary> /// <param name="property"></param> /// <returns></returns> protected JsonNameAttribute GetJsonPropertyAttribute(PropertyInfo property) { if (property == null) { throw new ArgumentNullException("property"); } object[] attributes = property.GetCustomAttributes(true); JsonNameAttribute jsonPropertyAttribute = null; bool ignore = false; foreach (object attribute in attributes) { if (attribute is ScriptIgnoreAttribute) { ignore = true; } if (attribute is JsonNameAttribute) { jsonPropertyAttribute = (JsonNameAttribute)attribute; } } JsonNameAttribute result = jsonPropertyAttribute ?? new JsonNameAttribute(); result.Ignored |= ignore; if (string.IsNullOrWhiteSpace(result.PropertyName)) { result.PropertyName = property.Name; } return(result); }