JsonCommaDelimitedArrayConverter.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.ComponentModel;
  3. using System.Text.Json;
  4. using System.Text.Json.Serialization;
  5. namespace MediaBrowser.Common.Json.Converters
  6. {
  7. /// <summary>
  8. /// Convert comma delimited string to array of type.
  9. /// </summary>
  10. /// <typeparam name="T">Type to convert to.</typeparam>
  11. public class JsonCommaDelimitedArrayConverter<T> : JsonConverter<T[]>
  12. {
  13. private readonly TypeConverter _typeConverter;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="JsonCommaDelimitedArrayConverter{T}"/> class.
  16. /// </summary>
  17. public JsonCommaDelimitedArrayConverter()
  18. {
  19. _typeConverter = TypeDescriptor.GetConverter(typeof(T));
  20. }
  21. /// <inheritdoc />
  22. public override T[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  23. {
  24. if (reader.TokenType == JsonTokenType.String)
  25. {
  26. var stringEntries = reader.GetString()?.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  27. if (stringEntries == null || stringEntries.Length == 0)
  28. {
  29. return Array.Empty<T>();
  30. }
  31. var entries = new T[stringEntries.Length];
  32. for (var i = 0; i < stringEntries.Length; i++)
  33. {
  34. entries[i] = (T)_typeConverter.ConvertFrom(stringEntries[i].Trim());
  35. }
  36. return entries;
  37. }
  38. return JsonSerializer.Deserialize<T[]>(ref reader, options);
  39. }
  40. /// <inheritdoc />
  41. public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options)
  42. {
  43. JsonSerializer.Serialize(writer, value, options);
  44. }
  45. }
  46. }