/// <summary> /// Find a serializer for the type defined on class declaration /// </summary> /// <param name="dataType">The data type to look for</param> /// <returns>The type of the serializer</returns> public static Type FindTypeSerializer(Type dataType) { LazyJsonAttributeSerializer jsonAttributeSerializer = null; Object[] jsonAttributeSerializerArray = dataType.GetCustomAttributes(typeof(LazyJsonAttributeSerializer), false); if (jsonAttributeSerializerArray.Length > 0) { jsonAttributeSerializer = (LazyJsonAttributeSerializer)jsonAttributeSerializerArray[0]; } if (jsonAttributeSerializer != null && jsonAttributeSerializer.SerializerType != null && jsonAttributeSerializer.SerializerType.IsSubclassOf(typeof(LazyJsonSerializerBase)) == true) { return(jsonAttributeSerializer.SerializerType); } return(null); }
/// <summary> /// Serialize an object to a json token by object property info /// </summary> /// <param name="data">The object to be serialized</param> /// <returns>The json token</returns> public static LazyJsonToken SerializeObject(Object data) { if (data == null) { return(new LazyJsonNull()); } Type dataType = data.GetType(); if (dataType.IsArray == true || dataType.IsGenericType == true) { return(SerializeToken(data)); } LazyJsonObject jsonObject = new LazyJsonObject(); List <String> alreadySerializer = new List <String>(); PropertyInfo[] propertyInfoArray = dataType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo propertyInfo in propertyInfoArray) { if (propertyInfo.GetMethod == null) { continue; } if (alreadySerializer.Contains(propertyInfo.Name) == true) { continue; } if (propertyInfo.GetCustomAttributes(typeof(LazyJsonAttributePropertyIgnore), false).Length > 0) { continue; } alreadySerializer.Add(propertyInfo.Name); Type jsonSerializerType = null; String propertyName = propertyInfo.Name; Object[] jsonAttributeBaseArray = propertyInfo.GetCustomAttributes(typeof(LazyJsonAttributeBase), false); foreach (Object attribute in jsonAttributeBaseArray) { if (attribute is LazyJsonAttributePropertyRename) { propertyName = ((LazyJsonAttributePropertyRename)attribute).Name; } else if (attribute is LazyJsonAttributeSerializer) { LazyJsonAttributeSerializer jsonAttributeSerializer = (LazyJsonAttributeSerializer)attribute; if (jsonAttributeSerializer.SerializerType != null && jsonAttributeSerializer.SerializerType.IsSubclassOf(typeof(LazyJsonSerializerBase)) == true) { jsonSerializerType = jsonAttributeSerializer.SerializerType; } } } if (jsonSerializerType != null) { jsonObject.Add(new LazyJsonProperty(propertyName, ((LazyJsonSerializerBase)Activator.CreateInstance(jsonSerializerType)).Serialize(propertyInfo.GetValue(data)))); } else { jsonObject.Add(new LazyJsonProperty(propertyName, SerializeToken(propertyInfo.GetValue(data)))); } } return(jsonObject); }