| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.ComponentModel; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | using System.Text.Json.Serialization; |
| | | 6 | | |
| | | 7 | | namespace Jellyfin.Extensions.Json.Converters |
| | | 8 | | { |
| | | 9 | | /// <summary> |
| | | 10 | | /// Convert delimited string to array of type. |
| | | 11 | | /// </summary> |
| | | 12 | | /// <typeparam name="T">Type to convert to.</typeparam> |
| | | 13 | | public abstract class JsonDelimitedCollectionConverter<T> : JsonConverter<IReadOnlyCollection<T>> |
| | | 14 | | { |
| | | 15 | | private readonly TypeConverter _typeConverter; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Initializes a new instance of the <see cref="JsonDelimitedCollectionConverter{T}"/> class. |
| | | 19 | | /// </summary> |
| | 23 | 20 | | protected JsonDelimitedCollectionConverter() |
| | | 21 | | { |
| | 23 | 22 | | _typeConverter = TypeDescriptor.GetConverter(typeof(T)); |
| | 23 | 23 | | } |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Gets the array delimiter. |
| | | 27 | | /// </summary> |
| | | 28 | | protected virtual char Delimiter { get; } |
| | | 29 | | |
| | | 30 | | /// <inheritdoc /> |
| | | 31 | | public override IReadOnlyCollection<T>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOption |
| | | 32 | | { |
| | 16 | 33 | | if (reader.TokenType == JsonTokenType.String) |
| | | 34 | | { |
| | | 35 | | // null got handled higher up the call stack |
| | 12 | 36 | | var stringEntries = reader.GetString()!.Split(Delimiter, StringSplitOptions.RemoveEmptyEntries); |
| | 12 | 37 | | if (stringEntries.Length == 0) |
| | | 38 | | { |
| | 2 | 39 | | return []; |
| | | 40 | | } |
| | | 41 | | |
| | 10 | 42 | | var typedValues = new List<T>(); |
| | 70 | 43 | | for (var i = 0; i < stringEntries.Length; i++) |
| | | 44 | | { |
| | | 45 | | try |
| | | 46 | | { |
| | 25 | 47 | | var parsedValue = _typeConverter.ConvertFromInvariantString(stringEntries[i].Trim()); |
| | 24 | 48 | | if (parsedValue is not null) |
| | | 49 | | { |
| | 24 | 50 | | typedValues.Add((T)parsedValue); |
| | | 51 | | } |
| | 24 | 52 | | } |
| | 1 | 53 | | catch (FormatException) |
| | | 54 | | { |
| | | 55 | | // Ignore unconvertible inputs |
| | 1 | 56 | | } |
| | | 57 | | } |
| | | 58 | | |
| | 10 | 59 | | if (typeToConvert.IsArray) |
| | | 60 | | { |
| | 6 | 61 | | return typedValues.ToArray(); |
| | | 62 | | } |
| | | 63 | | |
| | 4 | 64 | | return typedValues; |
| | | 65 | | } |
| | | 66 | | |
| | 4 | 67 | | return JsonSerializer.Deserialize<T[]>(ref reader, options); |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | /// <inheritdoc /> |
| | | 71 | | public override void Write(Utf8JsonWriter writer, IReadOnlyCollection<T>? value, JsonSerializerOptions options) |
| | | 72 | | { |
| | 34 | 73 | | JsonSerializer.Serialize(writer, value, options); |
| | 34 | 74 | | } |
| | | 75 | | } |
| | | 76 | | } |