| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Text.Json.Serialization.Metadata; |
| | | 6 | | |
| | | 7 | | namespace System.Text.Json.Serialization.Converters |
| | | 8 | | { |
| | | 9 | | internal sealed class IReadOnlyDictionaryOfTKeyTValueConverter<TDictionary, TKey, TValue> |
| | | 10 | | : DictionaryDefaultConverter<TDictionary, TKey, TValue> |
| | | 11 | | where TDictionary : IReadOnlyDictionary<TKey, TValue> |
| | | 12 | | where TKey : notnull |
| | | 13 | | { |
| | 0 | 14 | | private readonly bool _isDeserializable = typeof(TDictionary).IsAssignableFrom(typeof(Dictionary<TKey, TValue>)) |
| | | 15 | | |
| | | 16 | | protected override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) |
| | 0 | 17 | | { |
| | 0 | 18 | | Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)state.Current.ReturnValue!; |
| | | 19 | | |
| | 0 | 20 | | if (options.AllowDuplicateProperties) |
| | 0 | 21 | | { |
| | 0 | 22 | | dictionary[key] = value; |
| | 0 | 23 | | } |
| | | 24 | | else |
| | 0 | 25 | | { |
| | 0 | 26 | | if (!dictionary.TryAdd(key, value)) |
| | 0 | 27 | | { |
| | 0 | 28 | | ThrowHelper.ThrowJsonException_DuplicatePropertyNotAllowed(); |
| | | 29 | | } |
| | 0 | 30 | | } |
| | 0 | 31 | | } |
| | | 32 | | |
| | 0 | 33 | | internal override bool SupportsCreateObjectDelegate => false; |
| | | 34 | | protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state) |
| | 0 | 35 | | { |
| | 0 | 36 | | if (!_isDeserializable) |
| | 0 | 37 | | { |
| | 0 | 38 | | ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); |
| | | 39 | | } |
| | | 40 | | |
| | 0 | 41 | | state.Current.ReturnValue = new Dictionary<TKey, TValue>(); |
| | 0 | 42 | | } |
| | | 43 | | } |
| | | 44 | | } |