ManagedFusion.Serialization.Serializer.FromObject C# (CSharp) Method

FromObject() public method

Serializes the specified obj.
public FromObject ( object obj, ISerializerOptions options ) : object>.IDictionary
obj object The obj.
options ISerializerOptions
return object>.IDictionary
        public IDictionary<string, object> FromObject(object obj, ISerializerOptions options)
        {
            object value = SerializeValue(obj, 0 /* level */, options.MaxSerializableLevelsSupported ?? LevelsToSerialize);
            string modelName = null;

            // remove special case model name if found in output
            if (value is IDictionary<string, object> && ((IDictionary<string, object>)value).ContainsKey(ModelNameKey))
            {
                modelName = Convert.ToString(((IDictionary<string, object>)value)[ModelNameKey]);
                ((IDictionary<string, object>)value).Remove(ModelNameKey);
            }

            if (options.CheckForObjectName || !(value is IDictionary<string, object>) || !String.IsNullOrWhiteSpace(modelName))
            {
                string name = obj is ICollection ? "collection" : "object";

                // make sure the object isn't an easily handled primity type with IEnumerable
                if (Type.GetTypeCode(obj.GetType()) != TypeCode.Object)
                    name = "object";

                // make sure this type of dictionary is treated as an object
                if (obj is IDictionary<string, object>)
                    name = "object";

                // check for special case name from dictionary object
                if (!String.IsNullOrWhiteSpace(modelName))
                    name = modelName;

                // get what the object likes to be called
                if (obj.GetType().IsDefined(typeof(SerializableObjectAttribute), true))
                {
                    object[] attrs = obj.GetType().GetCustomAttributes(typeof(SerializableObjectAttribute), true);

                    if (attrs.Length > 0)
                    {
                        SerializableObjectAttribute attr = attrs[0] as SerializableObjectAttribute;
                        name = attr.Name;
                    }
                }

                IDictionary<string, object> response = new Dictionary<string, object>(1);
                response.Add(name, value);

                value = response;
            }

            return value as IDictionary<string, object>;
        }

Usage Example

        public void Simple_With_Name()
        {
            // arrange
            var expected = "test";
            var obj = new TestModel();

            var ser = new Serializer();
            var options = new SerlizerOptions { CheckForObjectName = true };

            // act
            var result = ser.FromObject(obj, options);

            // assert
            Assert.AreEqual(expected, result.Keys.First());
        }
All Usage Examples Of ManagedFusion.Serialization.Serializer::FromObject