using System;
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MediaBrowser.Common.Json.Converters
{
///
/// Convert comma delimited string to array of type.
///
/// Type to convert to.
public class JsonCommaDelimitedArrayConverter : JsonConverter
{
private readonly TypeConverter _typeConverter;
///
/// Initializes a new instance of the class.
///
public JsonCommaDelimitedArrayConverter()
{
_typeConverter = TypeDescriptor.GetConverter(typeof(T));
}
///
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();
}
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(ref reader, options);
}
///
public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, options);
}
}
}