public static Document Serialize(object item, SerializationMaskType mask = SerializationMaskType.Everything) { var doc = new Document { { Common.TYPE_KEY, item.GetType().AssemblyQualifiedName } }; var fields = Common.GetFields(item.GetType()).ToArray(); for (byte iField = 0; iField < fields.Length; iField++) { var field = fields.ElementAt(iField); if (field.IsStatic) { continue; } var maskAtt = field.GetAttribute <SerializationMaskAttribute>(); if (maskAtt != null && maskAtt.IsMaskValid(mask)) { continue; } var value = field.GetValue(item); if (value != null) { doc.Add(field.Name, SerializeField(value, mask)); } } return(doc); }
private static object SerializeField(object value, SerializationMaskType mask) { if (value == null) { return(null); } var type = value.GetType(); if (type.IsPrimitive || type == typeof(string)) { return(value); } if (type.GetInterfaces().Contains(typeof(IList))) { var list = (IList)value; var listData = new object[list.Count]; var iItem = 0; foreach (var item in list) { listData[iItem++] = SerializeField(item, mask); } return(listData); } if (type.GetInterfaces().Contains(typeof(IDictionary))) { var dict = (IDictionary)value; var dictData = new Dictionary <object, object>(); foreach (var key in dict.Keys) { dictData[SerializeField(key, mask)] = SerializeField(dict[key], mask); } return(dictData); } if (type.IsEnum) { return(value.ToString()); } if (type.IsClass || type.IsValueType) { return(Serialize(value, mask)); } throw new Exception(string.Format("Unsupported type {0}", type.Name)); }
private static DynamoDBEntry SerializeField(object value, SerializationMaskType mask) { if (value == null) { return(null); } var type = value.GetType(); if (IsPrimitive(type)) { return(ValueToPrimitive(value)); } if (type.GetInterfaces().Contains(typeof(IList))) { var list = (IList)value; var listOfEntries = new DynamoDBList(); foreach (var item in list) { listOfEntries.Add(SerializeField(item, mask)); } return(listOfEntries); } if (type.GetInterfaces().Contains(typeof(IDictionary))) { var dict = (IDictionary)value; var dictData = new Document(); foreach (var key in dict.Keys) { dictData[SerializeField(key, mask)] = SerializeField(dict[key], mask); } return(dictData); } if (type.IsEnum) { return(value.ToString()); } if (type.IsClass || type.IsValueType) { return(Serialize(value, mask)); } throw new Exception(string.Format("Unsupported type {0}", type.Name)); }
public static bool TrySerialize(object item, SerializationMaskType mask, out Dictionary <string, object> data, out string errorMessage) { try { data = Serialize(item, mask); errorMessage = string.Empty; return(true); } catch (Exception e) { errorMessage = e.Message; data = null; return(false); } }
public bool IsMaskValid(SerializationMaskType mask) { return((_mask & mask) != mask); }
public SerializationMaskAttribute(SerializationMaskType mask) { _mask = mask; }