Пример #1
0
        private bool ElementEquals(JsonElement element1, JsonElement element2)
        {
            if (!element1.ValueKind.Equals(element2.ValueKind))
            {
                return(false);
            }
            else
            {
                switch (element1.ValueKind)
                {
                case JsonValueKind.Array:
                    return(ArrayElementEquals(element1, element2));

                case JsonValueKind.Object:
                    return(ObjectElementEquals(element1, element2));

                case JsonValueKind.Undefined:
                case JsonValueKind.Null:
                case JsonValueKind.True:
                case JsonValueKind.False:
                    return(true);

                case JsonValueKind.Number:
                    return(element1.GetDecimal().Equals(element2.GetDecimal()));

                case JsonValueKind.String:
                    return(string.Equals(element1.GetString(), element2.GetString()));

                default:
                    throw new NotSupportedException($"JSON value kind not supported:  {element1.ValueKind}");
                }
            }
        }
Пример #2
0
        static object GetPropertyValue(JsonElement jsonElement)
        {
            switch (jsonElement.ValueKind)
            {
            case JsonValueKind.String:
                return(jsonElement.GetString());

            case JsonValueKind.Number:
                int integerOutput;

                if (jsonElement.TryGetInt32(out integerOutput))
                {
                    return(integerOutput);
                }
                else
                {
                    return(jsonElement.GetDecimal());
                }

            case JsonValueKind.True:
            case JsonValueKind.False:
                return(jsonElement.GetBoolean());

            case JsonValueKind.Null:
                return(null);

            case JsonValueKind.Object:
            case JsonValueKind.Array:
                return(ParseJsonElement(jsonElement));
            }

            throw new ArgumentException();
        }
Пример #3
0
        private string GetStringValue(JsonElement value)
        {
            var valueKind = value.ValueKind;

            if (valueKind == JsonValueKind.Array)
            {
                return(string.Empty);
            }

            if (valueKind == JsonValueKind.False || valueKind == JsonValueKind.True)
            {
                return(value.GetBoolean().ToString());
            }

            if (valueKind == JsonValueKind.Number)
            {
                return(value.GetDecimal().ToString());
            }

            if (valueKind == JsonValueKind.String)
            {
                return(value.GetString());
            }

            return(default);
Пример #4
0
        /// <summary>
        /// Get value of JsonElement
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>

        public static object GetValue(this JsonElement property)
        {
            switch (property.ValueKind)
            {
            case JsonValueKind.Array:
                throw new NotSupportedException("Array is not supported, use [FromBody] and Model instead");

            case JsonValueKind.False:
                return(false);

            case JsonValueKind.Null:
                return(null);

            case JsonValueKind.Number:
                return(property.GetDecimal());

            case JsonValueKind.Object:
                throw new NotSupportedException("Object is not supported, use [FromBody] and Model instead");

            case JsonValueKind.String:
                return(property.GetString());

            case JsonValueKind.True:
                return(true);

            case JsonValueKind.Undefined:
                return(null);

            default:
                throw new ArgumentException("Unkown property.ValueKind");
            }
        }
Пример #5
0
        public static void SetValueFromJson(this PropertyInfo property, Object obj, JsonElement value, string dateTimeFormat = null)
        {
            TypeCode typeCode = Type.GetTypeCode(property.PropertyType);

            switch (typeCode)
            {
            case TypeCode.Int32:
                int int32Value = value.GetInt32();
                property.SetValue(obj, int32Value);
                break;

            case TypeCode.Int64:
                long int64Value = value.GetInt64();
                property.SetValue(obj, int64Value);
                break;

            case TypeCode.Double:
                double doubleValue = value.GetDouble();
                property.SetValue(obj, doubleValue);
                break;

            case TypeCode.Decimal:
                decimal decimalValue = value.GetDecimal();
                property.SetValue(obj, decimalValue);
                break;

            case TypeCode.Boolean:
                bool boolValue = value.GetBoolean();
                property.SetValue(obj, boolValue);
                break;

            case TypeCode.DateTime:
                DateTime dateTimeValue;
                if (value.ValueKind == JsonValueKind.Null)
                {
                    dateTimeValue = DateTime.MinValue;
                }
                else if (!string.IsNullOrEmpty(dateTimeFormat))
                {
                    var stringDateTimeValue = value.GetString();
                    dateTimeValue = DateTime.ParseExact(stringDateTimeValue, dateTimeFormat, CultureInfo.InvariantCulture);
                }
                else
                {
                    dateTimeValue = value.GetDateTime();
                }

                property.SetValue(obj, dateTimeValue);
                break;

            case TypeCode.String:
                string stringValue = value.GetString();
                property.SetValue(obj, stringValue);
                break;

            default:
                //ThrowNotImplementedException(type); TODO: Сделать исключение.
                break;
            }
        }
Пример #6
0
        private object ReadValue(JsonElement element)
        {
            switch (element.ValueKind)
            {
            case JsonValueKind.Array:
                return(ReadArray(element));

            case JsonValueKind.False:
                return(false);

            case JsonValueKind.Null:
                return(null);

            case JsonValueKind.Number:
                return(element.GetDecimal());

            case JsonValueKind.Object:
                return(ReadObject(element));

            case JsonValueKind.String:
                return(element.GetString());

            case JsonValueKind.True:
                return(true);

            case JsonValueKind.Undefined:
                return(null);

            default:
                throw new ArgumentOutOfRangeException(nameof(element));
            }
        }
Пример #7
0
    /// <summary>
    /// 对JsonElement对象的辅助扩展
    /// </summary>
    /// <param name="o">对象</param>
    /// <returns>JSON字符串</returns>
    public static T Value <T>(this JsonElement json, string key)
    {
        JsonElement j = json.GetProperty(key);

        switch (j.ValueKind)
        {
        case JsonValueKind.Undefined:
            return(default(T));

        case JsonValueKind.Object:
            return((T)(Object)j);

        case JsonValueKind.Array:
            return((T)(Object)j);

        case JsonValueKind.String:
            return((T)(Object)j.GetString());

        case JsonValueKind.Number:
            return((T)(Object)j.GetDecimal());

        case JsonValueKind.True:
            return((T)(Object)true);

        case JsonValueKind.False:
            return((T)(Object)false);

        case JsonValueKind.Null:
            return(default(T));

        default:
            return((T)(Object)j);
        }
    }
Пример #8
0
        public static object GetValue(this JsonElement json, Type type)
        {
            switch (Type.GetTypeCode(type))
            {
            case TypeCode.Boolean: return(json.GetBoolean());

            case TypeCode.SByte: return(json.GetSByte());

            case TypeCode.Int16: return(json.GetInt16());

            case TypeCode.Int32: return(json.GetInt32());

            case TypeCode.Int64: return(json.GetInt64());

            case TypeCode.Byte: return(json.GetByte());

            case TypeCode.UInt16: return(json.GetUInt16());

            case TypeCode.UInt32: return(json.GetUInt32());

            case TypeCode.UInt64: return(json.GetUInt64());

            case TypeCode.Single: return(json.GetSingle());

            case TypeCode.Double: return(json.GetDouble());

            case TypeCode.Decimal: return(json.GetDecimal());

            case TypeCode.String: return(json.GetString());

            case TypeCode.DateTime: return(json.GetDateTime());
            }
            return(Convert.ChangeType(json.GetRawText(), type));
        }
Пример #9
0
 protected override dynamic FromJsonElement(JsonElement graphson)
 {
     if (graphson.ValueKind == JsonValueKind.String)
     {
         return(decimal.Parse(graphson.GetString(), CultureInfo.InvariantCulture));
     }
     return(graphson.GetDecimal());
 }
Пример #10
0
            private static object?ConvertObject(JsonElement token, OperationSymbol operationSymbol)
            {
                switch (token.ValueKind)
                {
                case JsonValueKind.Undefined: return(null);

                case JsonValueKind.String:
                    if (token.TryGetDateTime(out var dt))
                    {
                        return(dt);
                    }

                    if (token.TryGetDateTimeOffset(out var dto))
                    {
                        return(dto);
                    }

                    return(token.GetString());

                case JsonValueKind.Number: return(token.GetDecimal());

                case JsonValueKind.True: return(true);

                case JsonValueKind.False: return(false);

                case JsonValueKind.Null: return(null);

                case JsonValueKind.Object:
                {
                    if (token.TryGetProperty("EntityType", out var entityType))
                    {
                        return(token.ToObject <Lite <Entity> >(SignumServer.JsonSerializerOptions));
                    }

                    if (token.TryGetProperty("Type", out var type))
                    {
                        return(token.ToObject <ModifiableEntity>(SignumServer.JsonSerializerOptions));
                    }

                    var conv = CustomOperationArgsConverters.TryGetC(operationSymbol);

                    if (conv == null)
                    {
                        throw new InvalidOperationException("Impossible to deserialize request before executing {0}.\r\nConsider registering your own converter in 'CustomOperationArgsConverters'.\r\nReceived JSON:\r\n\r\n{1}".FormatWith(operationSymbol, token));
                    }

                    return(conv.GetInvocationListTyped().Select(f => conv(token)).NotNull().FirstOrDefault());
                }

                case JsonValueKind.Array:
                    var result = token.EnumerateArray().Select(t => ConvertObject(t, operationSymbol)).ToList();
                    return(result);

                default:
                    throw new UnexpectedValueException(token.ValueKind);
                }
            }
Пример #11
0
        public override void SerializePrimitive <T>(ref T val)
        {
            switch (val)
            {
            case bool:
                Unsafe.As <T, bool>(ref val) = currentNode.GetBoolean();
                break;

            case int:
                Unsafe.As <T, int>(ref val) = currentNode.GetInt32();
                break;

            case uint:
                Unsafe.As <T, uint>(ref val) = currentNode.GetUInt32();
                break;

            case float:
                Unsafe.As <T, float>(ref val) = currentNode.GetSingle();
                break;

            case double:
                Unsafe.As <T, double>(ref val) = currentNode.GetDouble();
                break;

            case long:
                Unsafe.As <T, long>(ref val) = currentNode.GetInt64();
                break;

            case ulong:
                Unsafe.As <T, ulong>(ref val) = currentNode.GetUInt64();
                break;

            case short:
                Unsafe.As <T, short>(ref val) = currentNode.GetInt16();
                break;

            case ushort:
                Unsafe.As <T, ushort>(ref val) = currentNode.GetUInt16();
                break;

            case char:
                Unsafe.As <T, char>(ref val) = (char)currentNode.GetUInt16();
                break;

            case sbyte:
                Unsafe.As <T, sbyte>(ref val) = currentNode.GetSByte();
                break;

            case byte:
                Unsafe.As <T, byte>(ref val) = currentNode.GetByte();
                break;

            case decimal:
                Unsafe.As <T, decimal>(ref val) = currentNode.GetDecimal();
                break;
            }
        }
Пример #12
0
 public SearchMetaData(JsonElement metaData)
 {
     CompletedIn = metaData.GetDecimal("completed_in");
     NextResults = metaData.GetString("next_results");
     Query       = metaData.GetString("query");
     RefreshUrl  = metaData.GetString("refresh_url");
     Count       = metaData.GetInt("count");
     MaxID       = (metaData.GetString("max_id_str") ?? string.Empty).GetULong();
     SinceID     = (metaData.GetString("since_id_str") ?? string.Empty).GetULong();
 }
Пример #13
0
        private Expression ParseTree <T>(
            JsonElement condition,
            ParameterExpression parm)
        {
            Expression left = null;
            var        gate = condition.GetProperty(nameof(condition)).GetString();

            JsonElement rules = condition.GetProperty(nameof(rules));

            Binder binder = gate == And ? (Binder)Expression.And : Expression.Or;

            Expression bind(Expression left, Expression right) =>
            left == null ? right : binder(left, right);

            foreach (var rule in rules.EnumerateArray())
            {
                if (rule.TryGetProperty(nameof(condition), out JsonElement check))
                {
                    var right = ParseTree <T>(rule, parm);
                    left = bind(left, right);
                    continue;
                }

                string @operator = rule.GetProperty(nameof(@operator)).GetString();
                string type      = rule.GetProperty(nameof(type)).GetString();
                string field     = rule.GetProperty(nameof(field)).GetString();

                JsonElement value = rule.GetProperty(nameof(value));

                var property = Expression.Property(parm, field);

                if (@operator == In)
                {
                    var    contains = MethodContains.MakeGenericMethod(typeof(string));
                    object val      = value.EnumerateArray().Select(e => e.GetString())
                                      .ToList();
                    var right = Expression.Call(
                        contains,
                        Expression.Constant(val),
                        property);
                    left = bind(left, right);
                }
                else
                {
                    object val = (type == StringStr || type == BooleanStr) ?
                                 (object)value.GetString() : value.GetDecimal();
                    var toCompare = Expression.Constant(val);
                    var right     = Expression.Equal(property, toCompare);
                    left = bind(left, right);
                }
            }

            return(left);
        }
Пример #14
0
        private static object GetGenericNumber(this JsonElement jsonElement)
        {
            // Attempt to parse the JSON Element as an Int32 first
            if (jsonElement.TryGetInt32(out int int32))
            {
                return(int32);
            }

            // Failing that, parse it as a Decimal instead
            return(jsonElement.GetDecimal());
        }
Пример #15
0
 public static bool IsTruthy(this JsonElement element)
 {
     return(element.ValueKind switch
     {
         JsonValueKind.Array => element.GetArrayLength() != 0,
         JsonValueKind.String => element.GetString() != string.Empty,
         JsonValueKind.Number => element.GetDecimal() != 0,
         JsonValueKind.True => true,
         JsonValueKind.False => false,
         JsonValueKind.Null => false,
         _ => throw new JsonLogicException($"Cannot determine truthiness of `{element.ValueKind}`.")
     });
Пример #16
0
 public static object ToObject(this JsonElement element, ColumnType columnType)
 {
     return(columnType switch
     {
         ColumnType.Boolean => element.GetBoolean(),
         ColumnType.Decimal => element.GetDecimal(),
         ColumnType.Integer => element.GetInt64(),
         ColumnType.String => element.GetString(),
         ColumnType.DateTime => element.GetDateTime(),
         _ => throw new ArgumentException($"Unsupported columnType conversion [{columnType}]",
                                          nameof(columnType))
     });
Пример #17
0
 private static Document PrintImpl(JsonElement element, IndentationOptions indentation)
 {
     return(element.ValueKind switch
     {
         JsonValueKind.Array => PrintArray(element, indentation),
         JsonValueKind.Object => PrintObject(element, indentation),
         JsonValueKind.String => JsonEscape(element.GetString()),
         JsonValueKind.Number => element.GetDecimal().ToString(),
         JsonValueKind.True => "true",
         JsonValueKind.False => "false",
         JsonValueKind.Null => "null",
         _ => throw new NotImplementedException()
     });
Пример #18
0
        public static decimal AsDecimal(JsonElement element)
        {
            switch (element.ValueKind)
            {
            case JsonValueKind.Number:
                return(element.GetDecimal());

            case JsonValueKind.String:
                return(decimal.Parse(element.GetString(), CultureInfo.InvariantCulture));

            default:
                throw new NotSupportedException();
            }
        }
Пример #19
0
        /// <summary>
        /// Determines JSON-compatible equivalence.
        /// </summary>
        /// <param name="a">The first element.</param>
        /// <param name="b">The second element.</param>
        /// <returns><code>true</code> if the element are equivalent; <code>false</code> otherwise.</returns>
        /// <exception cref="ArgumentOutOfRangeException">The <see cref="JsonElement.ValueKind"/> is not valid.</exception>
        public static bool IsEquivalentTo(this JsonElement a, JsonElement b)
        {
            if (a.ValueKind != b.ValueKind)
            {
                return(false);
            }
            switch (a.ValueKind)
            {
            case JsonValueKind.Object:
                var aProperties = a.EnumerateObject().ToList();
                var bProperties = b.EnumerateObject().ToList();
                if (aProperties.Count != bProperties.Count)
                {
                    return(false);
                }
                var grouped = aProperties.Concat(bProperties)
                              .GroupBy(p => p.Name)
                              .Select(g => g.ToList())
                              .ToList();
                return(grouped.All(g => g.Count == 2 && g[0].Value.IsEquivalentTo(g[1].Value)));

            case JsonValueKind.Array:
                var aElements = a.EnumerateArray().ToList();
                var bElements = b.EnumerateArray().ToList();
                if (aElements.Count != bElements.Count)
                {
                    return(false);
                }
                var zipped = aElements.Zip(bElements, (ae, be) => (ae, be));
                return(zipped.All(p => p.ae.IsEquivalentTo(p.be)));

            case JsonValueKind.String:
                return(a.GetString() == b.GetString());

            case JsonValueKind.Number:
                return(a.GetDecimal() == b.GetDecimal());

            case JsonValueKind.Undefined:
                return(false);

            case JsonValueKind.True:
            case JsonValueKind.False:
            case JsonValueKind.Null:
                return(true);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Пример #20
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
            });
Пример #21
0
        public static decimal ToDecimal(this JsonElement element)
        {
            if (element.ValueKind == JsonValueKind.Number)
            {
                return(element.GetDecimal());
            }

            if (element.ValueKind == JsonValueKind.String)
            {
                var str = element.ToString();

                if (decimal.TryParse(str, out var value))
                {
                    return(value);
                }

                throw new Exception($"Failed to convert string to decimal: {str}");
            }

            throw new Exception("Invalid element type, number or string expected.");
        }
Пример #22
0
    private static IRenderable GetPropertyValue(JsonElement property)
    {
        var    valueKind = property.ValueKind;
        object?value     = null;

        switch (valueKind)
        {
        case JsonValueKind.String:
            value = property.GetString();
            break;

        case JsonValueKind.True:
        case JsonValueKind.False:
            value = property.GetBoolean();
            break;

        case JsonValueKind.Number:
            value = property.GetDecimal();
            break;
        }
        return(new Markup(value?.ToString() ?? "-"));
    }
Пример #23
0
        private static object GetValue(JsonElement value)
        {
            switch (value.ValueKind)
            {
            case JsonValueKind.Object:
            {
                var output = new Dictionary <string, object>();

                foreach (var kvp in value.EnumerateObject())
                {
                    output.Add(kvp.Name, GetValue(kvp.Value));
                }

                return(output);
            }

            case JsonValueKind.Array:
                return(value.EnumerateArray().Select(GetValue).ToArray());

            case JsonValueKind.Null:
            case JsonValueKind.Undefined:
                return(null);

            case JsonValueKind.String:
                return(value.GetString());

            case JsonValueKind.Number:
                return(value.GetDecimal());

            case JsonValueKind.True:
                return(true);

            case JsonValueKind.False:
                return(false);

            default:
                return(value.GetRawText());
            }
        }
Пример #24
0
        private static object PrepareJsonElement(this JsonElement obj)
        {
            switch (obj.ValueKind)
            {
            case JsonValueKind.Object:
                IDictionary <string, object> expando = new ExpandoObject();
                foreach (var property in obj.EnumerateObject())
                {
                    expando.Add(property.Name, property.Value.PrepareJsonElement());
                }

                return(expando);

            case JsonValueKind.Array:
                return(obj.EnumerateArray().Select(jsonElement => jsonElement.PrepareJsonElement()));

            case JsonValueKind.String:
                return(obj.GetString());

            case JsonValueKind.Number:
                return(obj.GetDecimal());

            case JsonValueKind.True:
                return(true);

            case JsonValueKind.False:
                return(false);

            case JsonValueKind.Null:
                return(null);

            case JsonValueKind.Undefined:
                return(null);

            default:
                throw new ArgumentException();
            }
        }
        private bool valueEquals(JsonElement elem1, JsonElement elem2)
        {
            var valueKind = elem1.ValueKind;

            if (valueKind == JsonValueKind.True || valueKind == JsonValueKind.False)
            {
                return(elem1.GetBoolean() == elem2.GetBoolean());
            }
            else if (valueKind == JsonValueKind.Number)
            {
                return(elem1.GetDecimal() == elem2.GetDecimal());
            }
            else if (valueKind == JsonValueKind.String)
            {
                return(elem1.GetString() == elem2.GetString());
            }
            else if (valueKind == JsonValueKind.Null)
            {
                return(true);
            }

            return(false);
        }
Пример #26
0
        /// <summary>
        /// Writes a <see cref="JsonElement"/> to the stream.
        /// </summary>
        /// <param name="writer">The JSON stream writer.</param>
        /// <param name="element">The element to write.</param>
        /// <exception cref="ArgumentOutOfRangeException">The <see cref="JsonElement.ValueKind"/> is not valid.</exception>
        public static void WriteValue(this Utf8JsonWriter writer, JsonElement element)
        {
            switch (element.ValueKind)
            {
            case JsonValueKind.Object:
                WriteObject(writer, element);
                break;

            case JsonValueKind.Array:
                WriteArray(writer, element);
                break;

            case JsonValueKind.String:
                writer.WriteStringValue(element.GetString());
                break;

            case JsonValueKind.Number:
                writer.WriteNumberValue(element.GetDecimal());
                break;

            case JsonValueKind.True:
                writer.WriteBooleanValue(true);
                break;

            case JsonValueKind.False:
                writer.WriteBooleanValue(false);
                break;

            case JsonValueKind.Null:
                writer.WriteNullValue();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Пример #27
0
 public decimal?GetFloatValue() => _jsonNode.GetDecimal();
Пример #28
0
 private static void InsertDataTableInternal(DataTable dt, DataRow dr, JsonElement elem, string prefix, string column)
 {
     if (elem.ValueKind == JsonValueKind.Array)
     {
         bool firstElem = true;
         foreach (var item in elem.EnumerateArray())
         {
             if (column == null)
             {
                 dr = dt.NewRow();
                 dt.Rows.Add(dr);
                 InsertDataTableInternal(dt, dr, item, prefix, column);
             }
             else
             {
                 if (!firstElem)
                 {
                     dr = dt.NewRow();
                     dt.Rows.Add(dr);
                 }
                 firstElem = false;
                 string fullName = string.Concat(prefix, column, "[]");
                 InsertDataTableInternal(dt, dr, item, fullName, null);
             }
         }
     }
     else if (elem.ValueKind == JsonValueKind.Object)
     {
         if (dr == null)
         {
             dr = dt.NewRow();
             dt.Rows.Add(dr);
         }
         foreach (var prop in elem.EnumerateObject())
         {
             InsertDataTableInternal(dt, dr, prop.Value, prefix, $"{column}.{prop.Name}");
         }
     }
     else if (elem.ValueKind != JsonValueKind.Null && elem.ValueKind != JsonValueKind.Undefined)
     {
         string     fullName = string.Concat(prefix, column);
         DataColumn dc       = null;
         if (dt.Columns.Contains(fullName))
         {
             dc = dt.Columns[fullName];
         }
         if (elem.ValueKind == JsonValueKind.False || elem.ValueKind == JsonValueKind.True)
         {
             if (dc == null)
             {
                 dc = dt.Columns.Add(fullName, typeof(bool));
             }
             dr[dc] = elem.GetBoolean();
         }
         if (elem.ValueKind == JsonValueKind.Number)
         {
             if (dc == null)
             {
                 dc = dt.Columns.Add(fullName, typeof(decimal));
             }
             dr[dc] = elem.GetDecimal();
         }
         if (elem.ValueKind == JsonValueKind.String)
         {
             if (dc == null)
             {
                 dc = dt.Columns.Add(fullName, typeof(string));
             }
             dr[dc] = elem.GetString();
         }
     }
 }
Пример #29
0
        public static object ToObject(this JsonElement element, Type type)
        {
            object result = null;

            var nonNullType = Nullable.GetUnderlyingType(type);

            if (nonNullType != null)
            {
                type = nonNullType;
            }

            switch (Type.GetTypeCode(type))
            {
            case TypeCode.Boolean:
                result = element.GetBoolean();
                break;

            case TypeCode.Byte:
                result = element.GetByte();
                break;

            case TypeCode.SByte:
                result = element.GetSByte();
                break;

            case TypeCode.Int16:
                result = element.GetInt16();
                break;

            case TypeCode.UInt16:
                result = element.GetUInt16();
                break;

            case TypeCode.Int32:
                result = element.GetInt32();
                break;

            case TypeCode.UInt32:
                result = element.GetUInt32();
                break;

            case TypeCode.Int64:
                result = element.GetInt64();
                break;

            case TypeCode.UInt64:
                result = element.GetUInt64();
                break;

            case TypeCode.Single:
                result = element.GetSingle();
                break;

            case TypeCode.Double:
                result = element.GetDouble();
                break;

            case TypeCode.Decimal:
                result = element.GetDecimal();
                break;

            case TypeCode.DateTime:
                result = element.GetDateTime();
                break;

            case TypeCode.String:
                result = element.GetString();
                break;

            default:
                if (type == typeof(Guid))
                {
                    result = element.GetGuid();
                    break;
                }

                throw new NotImplementedException();
            }

            if (nonNullType != null)
            {
                return(result.ToNullable());
            }

            return(result);
        }
Пример #30
0
 private static object DeserializeJsonValue(Type type, JsonElement value)
 {
     if (value.ValueKind == JsonValueKind.Null &&
         (type == typeof(string) || Nullable.GetUnderlyingType(type) != null))
     {
         return(null);
     }
     else if (type == typeof(bool) || type == typeof(bool?))
     {
         return(value.GetBoolean());
     }
     else if (type == typeof(byte) || type == typeof(byte?))
     {
         return(value.GetByte());
     }
     else if (type == typeof(short) || type == typeof(short?))
     {
         return(value.GetInt16());
     }
     else if (type == typeof(ushort) || type == typeof(ushort?))
     {
         return(value.GetUInt16());
     }
     else if (type == typeof(int) || type == typeof(int?))
     {
         return(value.GetInt32());
     }
     else if (type == typeof(uint) || type == typeof(uint?))
     {
         return(value.GetUInt32());
     }
     else if (type == typeof(long) || type == typeof(long?))
     {
         return(value.GetInt64());
     }
     else if (type == typeof(ulong) || type == typeof(ulong?))
     {
         return(value.GetUInt64());
     }
     else if (type == typeof(float) || type == typeof(float?))
     {
         return(value.GetSingle());
     }
     else if (type == typeof(double) || type == typeof(double?))
     {
         return(value.GetDouble());
     }
     else if (type == typeof(decimal) || type == typeof(decimal?))
     {
         return(value.GetDecimal());
     }
     else if (type == typeof(DateTime) || type == typeof(DateTime?))
     {
         return(value.GetDateTime());
     }
     else if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?))
     {
         return(value.GetDateTimeOffset());
     }
     else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?))
     {
         return(TimeSpan.Parse(value.GetString()));
     }
     else if (type == typeof(string))
     {
         return(value.GetString());
     }
     else
     {
         return(JsonSerializer.Deserialize(value.GetRawText(), type));
     }
 }