| | | 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.Diagnostics; |
| | | 6 | | using System.Text.Json.Serialization.Metadata; |
| | | 7 | | |
| | | 8 | | namespace System.Text.Json.Serialization.Converters |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Converter for <cref>System.Collections.Generic.ICollection{TElement}</cref>. |
| | | 12 | | /// </summary> |
| | | 13 | | internal sealed class ICollectionOfTConverter<TCollection, TElement> |
| | | 14 | | : IEnumerableDefaultConverter<TCollection, TElement> |
| | | 15 | | where TCollection : ICollection<TElement> |
| | | 16 | | { |
| | 0 | 17 | | internal override bool CanPopulate => true; |
| | | 18 | | |
| | | 19 | | protected override void Add(in TElement value, ref ReadStack state) |
| | 0 | 20 | | { |
| | 0 | 21 | | TCollection collection = (TCollection)state.Current.ReturnValue!; |
| | 0 | 22 | | collection.Add(value); |
| | 0 | 23 | | if (IsValueType) |
| | 0 | 24 | | { |
| | 0 | 25 | | state.Current.ReturnValue = collection; |
| | 0 | 26 | | }; |
| | 0 | 27 | | } |
| | | 28 | | |
| | | 29 | | protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOp |
| | 0 | 30 | | { |
| | 0 | 31 | | base.CreateCollection(ref reader, ref state, options); |
| | 0 | 32 | | TCollection returnValue = (TCollection)state.Current.ReturnValue!; |
| | 0 | 33 | | if (returnValue.IsReadOnly) |
| | 0 | 34 | | { |
| | 0 | 35 | | state.Current.ReturnValue = null; // clear out for more accurate JsonPath reporting. |
| | 0 | 36 | | ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); |
| | | 37 | | } |
| | 0 | 38 | | } |
| | | 39 | | |
| | | 40 | | internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) |
| | 0 | 41 | | { |
| | | 42 | | // Deserialize as List<T> for interface types that support it. |
| | 0 | 43 | | if (jsonTypeInfo.CreateObject is null && Type.IsAssignableFrom(typeof(List<TElement>))) |
| | 0 | 44 | | { |
| | 0 | 45 | | Debug.Assert(Type.IsInterface); |
| | 0 | 46 | | jsonTypeInfo.CreateObject = () => new List<TElement>(); |
| | 0 | 47 | | } |
| | 0 | 48 | | } |
| | | 49 | | } |
| | | 50 | | } |