aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs
diff options
context:
space:
mode:
authorStan <stanislav.ionascu@gmail.com>2020-10-28 13:18:05 +0100
committerGitHub <noreply@github.com>2020-10-28 13:18:05 +0100
commit3bb8884e164857af01909d0f414f55ecf2a4f1e0 (patch)
treef03482a03d8523a17c36d74006bea35a8c7141d1 /MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs
parentcd4641dca02bae552cc7ea1942b0efbd4b791bcb (diff)
parentbe2f27a0695e5f3102f79a2e246e971682cff603 (diff)
Merge branch 'master' into bdiso-playback
Diffstat (limited to 'MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs')
-rw-r--r--MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs53
1 files changed, 53 insertions, 0 deletions
diff --git a/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs
new file mode 100644
index 000000000..bf7048c37
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonCommaDelimitedArrayConverter.cs
@@ -0,0 +1,53 @@
+using System;
+using System.ComponentModel;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ /// <summary>
+ /// Convert comma delimited string to array of type.
+ /// </summary>
+ /// <typeparam name="T">Type to convert to.</typeparam>
+ public class JsonCommaDelimitedArrayConverter<T> : JsonConverter<T[]>
+ {
+ private readonly TypeConverter _typeConverter;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="JsonCommaDelimitedArrayConverter{T}"/> class.
+ /// </summary>
+ public JsonCommaDelimitedArrayConverter()
+ {
+ _typeConverter = TypeDescriptor.GetConverter(typeof(T));
+ }
+
+ /// <inheritdoc />
+ public override T[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.String)
+ {
+ var stringEntries = reader.GetString()?.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
+ if (stringEntries == null || stringEntries.Length == 0)
+ {
+ return Array.Empty<T>();
+ }
+
+ var entries = new T[stringEntries.Length];
+ for (var i = 0; i < stringEntries.Length; i++)
+ {
+ entries[i] = (T)_typeConverter.ConvertFrom(stringEntries[i].Trim());
+ }
+
+ return entries;
+ }
+
+ return JsonSerializer.Deserialize<T[]>(ref reader, options);
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options)
+ {
+ JsonSerializer.Serialize(writer, value, options);
+ }
+ }
+} \ No newline at end of file