예제 #1
0
 /// <summary>
 /// Returns the value as a dictionary if the current value represents an object.
 /// Otherwise returns null.
 /// </summary>
 public IDictionary <string, DynamicValue> ToDictionary()
 {
     if (!(_value is IDictionary <string, object> dict))
     {
         return(null);
     }
     return(DynamicDictionary.Create(dict));
 }
예제 #2
0
        public T Get <T>(string path)
        {
            var dynamicDictionary = Value switch
            {
                DynamicDictionary v => v,
                IDictionary <string, object> v => DynamicDictionary.Create(v),
                _ => null
            };

            return(dynamicDictionary == null ? default : dynamicDictionary.Get <T>(path));
        }
예제 #3
0
        /// <summary>
        /// Returns the value as a dictionary if the current value represents an object.
        /// Otherwise returns null.
        /// </summary>
        public IDictionary <string, DynamicValue> ToDictionary()
        {
            if (_value is IDictionary <string, object> dict)
            {
                return(DynamicDictionary.Create(dict));
            }
            else if (_value is JsonElement e && e.ValueKind == JsonValueKind.Object)
            {
                var d = e.EnumerateObject()
                        .Aggregate(new Dictionary <string, object>(), (dictionary, je) =>
                {
                    dictionary.Add(je.Name, je.Value);
                    return(dictionary);
                });
                return(DynamicDictionary.Create(d));
            }

            return(null);
        }
예제 #4
0
        public static object ConsumeJsonElement(Type targetReturnType, JsonElement e)
        {
            // ReSharper disable once HeapView.BoxingAllocation
            object ParseNumber(JsonElement el)
            {
                if (el.TryGetInt64(out var l))
                {
                    return(l);
                }

                return(el.GetDouble());
            }

            return(targetReturnType switch
            {
                _ when targetReturnType == typeof(bool) => e.GetBoolean(),
                _ when targetReturnType == typeof(byte) => e.GetByte(),
                _ when targetReturnType == typeof(decimal) => e.GetDecimal(),
                _ when targetReturnType == typeof(double) => e.GetDouble(),
                _ when targetReturnType == typeof(Guid) => e.GetGuid(),
                _ when targetReturnType == typeof(short) => e.GetInt16(),
                _ when targetReturnType == typeof(int) => e.GetInt32(),
                _ when targetReturnType == typeof(long) => e.GetInt64(),
                _ when targetReturnType == typeof(float) => e.GetSingle(),
                _ when targetReturnType == typeof(string) => e.GetString(),
                _ when targetReturnType == typeof(DateTime) => e.GetDateTime(),
                _ when targetReturnType == typeof(DateTimeOffset) => e.GetDateTimeOffset(),
                _ when targetReturnType == typeof(ushort) => e.GetUInt16(),
                _ when targetReturnType == typeof(uint) => e.GetUInt32(),
                _ when targetReturnType == typeof(ulong) => e.GetUInt64(),
                _ when targetReturnType == typeof(sbyte) => e.GetSByte(),
                _ when targetReturnType == typeof(DynamicDictionary) => DynamicDictionary.Create(e),
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Array =>
                e.EnumerateArray().Select(je => ConsumeJsonElement(targetReturnType, je)).ToArray(),
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Object => e.ToDictionary(),
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.True => true,
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.False => false,
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Null => null,
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.String => e.GetString(),
                _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Number => ParseNumber(e),
                _ => null
            });
예제 #5
0
        internal bool TryParse(object defaultValue, Type targetReturnType, object value, out object newObject)
        {
            newObject = defaultValue;
            if (value == null)
            {
                return(false);
            }

            if (targetReturnType.IsGenericType && targetReturnType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                targetReturnType = targetReturnType.GenericTypeArguments[0];
            }

            try
            {
                var valueType = value.GetType();
                if (targetReturnType.IsArray && value is DynamicValue v)
                {
                    value     = v.Value;
                    valueType = value.GetType();
                }
                if (targetReturnType.IsArray)
                {
                    if (!valueType.IsArray)
                    {
                        return(false);
                    }
                    var ar          = (object[])value;
                    var t           = targetReturnType.GetElementType();
                    var objectArray = ar
                                      .Select(a => TryParse(defaultValue, t, a, out var o) ? o : null)
                                      .Where(a => a != null)
                                      .ToArray();

                    var arr = Array.CreateInstance(t, objectArray.Length);
                    Array.Copy(objectArray, arr, objectArray.Length);
                    newObject = arr;
                    return(true);
                }

                if (valueType.IsAssignableFrom(targetReturnType))
                {
                    newObject = value;
                    return(true);
                }

                var stringValue = value as string;

                if (targetReturnType == typeof(DateTime) &&
                    DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out var result))
                {
                    newObject = result;
                    return(true);
                }
                if (stringValue != null)
                {
                    if (targetReturnType == typeof(object))
                    {
                        newObject = Convert.ChangeType(value, targetReturnType);
                        return(true);
                    }

                    var converter = TypeDescriptor.GetConverter(targetReturnType);
                    if (converter.IsValid(stringValue))
                    {
                        newObject = converter.ConvertFromInvariantString(stringValue);
                        return(true);
                    }
                }
                else if (value is DynamicValue dv)
                {
                    return(dv.TryParse(defaultValue, targetReturnType, dv.Value, out newObject));
                }
                else if (targetReturnType == typeof(string))
                {
                    newObject = Convert.ChangeType(value, TypeCode.String, CultureInfo.InvariantCulture);
                    return(true);
                }
                else if (valueType.IsValueType)
                {
                    newObject = Convert.ChangeType(_value, targetReturnType);
                    return(true);
                }
                else if (targetReturnType == typeof(DynamicDictionary) && valueType == typeof(Dictionary <string, object>))
                {
                    newObject = DynamicDictionary.Create(value as Dictionary <string, object>);
                    return(true);
                }

                else if (targetReturnType == typeof(object))
                {
                    newObject = value;
                    return(true);
                }
            }
            catch
            {
                return(false);
            }
            return(false);
        }
예제 #6
0
 private static ElasticsearchResponse <DynamicDictionary> ToDynamicResponse(ElasticsearchResponse <Dictionary <string, object> > response)
 {
     return(CloneFrom(response, response.Response != null ? DynamicDictionary.Create(response.Response) : null));
 }
예제 #7
0
        /// <summary>
        /// Attempts to convert the value to type of T, failing to do so will return the defaultValue.
        /// </summary>
        /// <typeparam name="T">When no default value is supplied, required to supply the default type</typeparam>
        /// <param name="defaultValue">Optional parameter for default value, if not given it returns default of type T</param>
        /// <returns>If value is not null, value is returned, else default value is returned</returns>
        public T TryParse <T>(T defaultValue = default(T))
        {
            var type = typeof(T);

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                type = type.GenericTypeArguments[0];
            }

            if (HasValue)
            {
                try
                {
                    var valueType = _value.GetType();
                    if (valueType.IsAssignableFrom(typeof(T)))
                    {
                        return((T)_value);
                    }

                    var stringValue = _value as string;

                    if (type == typeof(DateTime))
                    {
                        if (DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out var result))
                        {
                            return((T)(object)result);
                        }
                    }
                    else if (stringValue != null)
                    {
                        if (type == typeof(object))
                        {
                            return((T)Convert.ChangeType(_value, type));
                        }

                        var converter = TypeDescriptor.GetConverter(type);
                        if (converter.IsValid(stringValue))
                        {
                            return((T)converter.ConvertFromInvariantString(stringValue));
                        }
                    }
                    else if (type == typeof(string))
                    {
                        return((T)Convert.ChangeType(_value, TypeCode.String, CultureInfo.InvariantCulture));
                    }
                    else if (valueType.IsValueType)
                    {
                        return((T)Convert.ChangeType(_value, type));
                    }
                    else if (type == typeof(DynamicDictionary) && valueType == typeof(Dictionary <string, object>))
                    {
                        return((T)(object)DynamicDictionary.Create(_value as Dictionary <string, object>));
                    }
                    else if (type == typeof(object))
                    {
                        return((T)_value);
                    }
                }
                catch
                {
                    return(defaultValue);
                }
            }

            return(defaultValue);
        }