Example #1
0
        private MessagePackObject CreateMessagePackObject(object value)
        {
            var type = (value?.GetType() ?? typeof(string)).GetTypeInfo();

            if (_typedMessagePackObjectFactories.TryGetValue(type.AsType(), out var factory))
            {
                return(factory.Invoke(value));
            }

            if (type.IsEnum)
            {
                return(new MessagePackObject(value.ToString()));
            }

            if (value is ExpandoObject || value is IDictionary <string, object> )
            {
                var obj = (IDictionary <string, object>)value;

                var dictionary = obj.ToDictionary(x => new MessagePackObject(x.Key), x => CreateMessagePackObject(x.Value));

                return(new MessagePackObject(new MessagePackObjectDictionary(dictionary)));
            }

            if (type.IsArray)
            {
                var obj = (object[])value;

                var array = obj.Select(x => CreateMessagePackObject(x)).ToArray();

                return(new MessagePackObject(array));
            }

            if (type.GetInterfaces().Any(x => x == typeof(IEnumerable)))
            {
                var list = new List <MessagePackObject>();

                foreach (var item in (IEnumerable)value)
                {
                    list.Add(CreateMessagePackObject(item));
                }

                return(new MessagePackObject(list));
            }

            if (type.IsAnonymous())
            {
                var properties = type.GetProperties(); // heavy

                var dictionary = properties.ToDictionary(x => new MessagePackObject(x.Name), x => CreateMessagePackObject(x.GetValue(value)));

                return(new MessagePackObject(new MessagePackObjectDictionary(dictionary)));
            }

            var objects = TypeAccessor.GetValueGetter(type.AsType())
                          .ToDictionary(x => new MessagePackObject(x.Key), x => CreateMessagePackObject(x.Value.Invoke(value)));

            return(new MessagePackObject(new MessagePackObjectDictionary(objects)));
        }