Exemplo n.º 1
0
        private Array ToArray(Type type)
        {
            var length                 = Element.GetArrayLength();
            var array                  = (Array)Activator.CreateInstance(type.MakeArrayType(), length);
            var enumerator             = Element.EnumerateArray();
            var index                  = 0;
            var isJsonElement          = type == typeof(JsonElement);
            var isDynamic              = type == typeof(object);
            var isJsonElementOrDynamic = isJsonElement || isDynamic;

            while (enumerator.MoveNext())
            {
                object value = enumerator.Current.ValueKind switch
                {
                    JsonValueKind.False when !isJsonElementOrDynamic => false,
                       JsonValueKind.True when !isJsonElementOrDynamic => true,
                       JsonValueKind.Number when !isJsonElementOrDynamic => enumerator.Current.GetDecimal(),
                       JsonValueKind.String when !isJsonElementOrDynamic => enumerator.Current.GetString(),
                       _ when isJsonElement => enumerator.Current,
                       _ when isDynamic => DynamicJsonElement.From(enumerator.Current, Options),
                    _ => enumerator.Current.GetRawText()
                };

                if (!isJsonElementOrDynamic)
                {
                    value = Convert.ChangeType(value, type);
                }

                array.SetValue(value, index++);
            }

            return(array);
        }
 public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
 => DynamicJsonElement.From(JsonSerializer.Deserialize <JsonElement>(ref reader, options));