Exemplo n.º 1
0
        public override Dictionary <TKey, TValue> Read(
            ref Utf8JsonReader reader,
            Type typeToConvert,
            JsonSerializerOptions options)
        {
            if (reader.TokenType != JsonTokenType.StartObject)
            {
                throw new JsonException();
            }
            var dictionary = new Dictionary <TKey, TValue>();

            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndObject)
                {
                    return(dictionary);
                }

                // Get the key.
                if (reader.TokenType != JsonTokenType.PropertyName)
                {
                    throw new JsonException();
                }

                var keyValue = reader.GetString();

                if (keyValue is null)
                {
                    throw new JsonException("Key was null.");
                }

                // TODO: This is all very basic
                TKey key;

                if (typeof(TKey) == typeof(string))
                {
                    key = (TKey)Activator.CreateInstance(typeof(string), keyValue.ToCharArray());
                }
                else if (typeof(TKey) == typeof(IndexName))
                {
                    key = IndexName.Parse(keyValue) as TKey;
                }
                else if (typeof(TKey) == typeof(Field))
                {
                    key = new Field(keyValue) as TKey;
                }
                else if (typeof(TKey) == typeof(TaskId))
                {
                    key = new TaskId(keyValue) as TKey;
                }
                else if (typeof(TKey) == typeof(PropertyName))
                {
                    key = new PropertyName(keyValue) as TKey;
                }
                else
                {
                    throw new JsonException("Unsupported dictionary key");
                    //key = (TKey)Activator.CreateInstance(typeof(TKey),
                    //	BindingFlags.Instance,
                    //	null,
                    //	new object[] { propertyName },
                    //	null);
                }

                // Get the value.
                TValue value;
                if (_valueConverter != null)
                {
                    reader.Read();
                    value = _valueConverter.Read(ref reader, _valueType, options);
                }
                else
                {
                    value = JsonSerializer.Deserialize <TValue>(ref reader, options);
                }

                // Add to dictionary.
                dictionary.Add(key, value);
            }

            return(dictionary);
        }