/// <summary> /// Serialize an instance to a JSON value. /// </summary> /// <param name="instance">The instance to serialize.</param> /// <returns>The serialized JSON value.</returns> /// <param name="ignoreCustomSerialization"> /// A value to indicate whether or not custom serialization should be /// ignored if the instance implements /// ICustomMobileServiceTableSerialization. This flag is used by /// implementations of ICustomMobileServiceTableSerialization that /// want to invoke the default serialization behavior. /// </param> public static JToken Serialize(object instance, bool ignoreCustomSerialization) { if (instance == null) { throw new ArgumentNullException("instance"); } // If the instance implements // ICustomMobileServiceTableSerialization, allow it to handle its // own serialization. if (!ignoreCustomSerialization) { ICustomMobileServiceTableSerialization custom = instance as ICustomMobileServiceTableSerialization; if (custom != null) { return(custom.Serialize()); } } // Get the Mobile Services specific type info SerializableType type = SerializableType.Get(instance.GetType()); // Create a new JSON object to represent the instance JObject obj = new JObject(); foreach (SerializableMember member in type.Members.Values.OrderBy(m => m.Order)) { // Get the value to serialize object value = member.GetValue(instance); if (member.Converter != null) { // If there's a user defined converter, we can apply that // and set the value directly. obj.Set(member.Name, member.Converter.ConvertToJson(value)); } else if (member == type.IdMember && SerializableType.IsDefaultIdValue(value)) { // Special case the ID member so we don't write out any // value if wasn't set (i.e., has a 0 or null value). This // allows us flexibility for the type of the ID column // which is currently a long in SQL but could someday be a // GUID in something like a document database. At some // point we might also change the server to quietly ignore // default values for the ID column on insert. } else if (!obj.TrySet(member.Name, value)) { throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, Resources.MobileServiceTableSerializer_Serialize_UnknownType, member.Name, member.Type.FullName, type.Type.Name), "instance"); } } return(obj); }