Skip to content

Instantly share code, notes, and snippets.

@alexpeta
Created February 25, 2014 11:33
Show Gist options
  • Select an option

  • Save alexpeta/9207293 to your computer and use it in GitHub Desktop.

Select an option

Save alexpeta/9207293 to your computer and use it in GitHub Desktop.
Simple Object mapper for ParseObject objects
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class ParseObjectMemberAttribute : Attribute
{
public string Key { get; private set; }
public ParseObjectMemberAttribute() : this(null)
{
}
public ParseObjectMemberAttribute(string key = null)
{
Key = key;
}
}
public interface IParseMapper
{
ParseObject GetParseObject<T>(T o) where T : class, new();
T GetObjectFromParse<T>(ParseObject po) where T : class, new();
}
public class ParseMapper : IParseMapper
{
private IEnumerable<KeyValuePair<string, object>> GetObjectPropertyMappingForParse(object obj)
{
if (object.ReferenceEquals(obj, null))
{
throw new ArgumentNullException("obj");
}
List<KeyValuePair<string, object>> result = new List<KeyValuePair<string, object>>();
Type type = obj.GetType();
foreach (PropertyInfo pi in type.GetRuntimeProperties())
{
IEnumerable<Attribute> propertyAttributes = pi.GetCustomAttributes();
if (propertyAttributes.Any(a => a.GetType() == typeof(ParseObjectMemberAttribute)))
{
result.Add(new KeyValuePair<string, object>(pi.Name, pi.GetValue(obj)));
}
}
return result;
}
public ParseObject GetParseObject<T>(T o)
where T : class, new()
{
ParseObject po = new ParseObject(o.GetType().Name);
var propertiesMappingList = this.GetObjectPropertyMappingForParse(o);
foreach (var map in propertiesMappingList)
{
po.Add(map.Key, map.Value);
}
return po;
}
public T GetObjectFromParse<T>(ParseObject po)
where T : class, new()
{
T result = Activator.CreateInstance<T>();
Type type = typeof(T);
IEnumerable<PropertyInfo> properties = type.GetRuntimeProperties();
foreach (var pi in properties)
{
Attribute customAttribute = pi.GetCustomAttributes()
.FirstOrDefault(a => a.GetType() == typeof(ParseObjectMemberAttribute));
ParseObjectMemberAttribute casted = customAttribute as ParseObjectMemberAttribute;
if (casted == null)
{
continue;
}
string key = string.IsNullOrEmpty(casted.Key) ? pi.Name : casted.Key;
pi.SetValue(result, po[key]);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment