JsonPipeDelimitedArrayConverter.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 Pipe delimited string to array of type.
  9. /// </summary>
  10. /// <typeparam name="T">Type to convert to.</typeparam>
  11. public class JsonPipeDelimitedArrayConverter<T> : JsonConverter<T[]>
  12. {
  13. private readonly TypeConverter _typeConverter;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="JsonPipeDelimitedArrayConverter{T}"/> class.
  16. /// </summary>
  17. public JsonPipeDelimitedArrayConverter()
  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.Null)
  25. {
  26. return Array.Empty<T>();
  27. }
  28. if (reader.TokenType == JsonTokenType.String)
  29. {
  30. // GetString can't return null here because we already handled it above
  31. var stringEntries = reader.GetString()!.Split('|', StringSplitOptions.RemoveEmptyEntries);
  32. if (stringEntries.Length == 0)
  33. {
  34. return Array.Empty<T>();
  35. }
  36. var parsedValues = new object[stringEntries.Length];
  37. var convertedCount = 0;
  38. for (var i = 0; i < stringEntries.Length; i++)
  39. {
  40. try
  41. {
  42. parsedValues[i] = _typeConverter.ConvertFrom(stringEntries[i].Trim());
  43. convertedCount++;
  44. }
  45. catch (FormatException)
  46. {
  47. // TODO log when upgraded to .Net6
  48. // https://github.com/dotnet/runtime/issues/42975
  49. // _logger.LogDebug(e, "Error converting value.");
  50. }
  51. }
  52. var typedValues = new T[convertedCount];
  53. var typedValueIndex = 0;
  54. for (var i = 0; i < stringEntries.Length; i++)
  55. {
  56. if (parsedValues[i] != null)
  57. {
  58. typedValues.SetValue(parsedValues[i], typedValueIndex);
  59. typedValueIndex++;
  60. }
  61. }
  62. return typedValues;
  63. }
  64. // can't return null here because we already handled it above
  65. return JsonSerializer.Deserialize<T[]>(ref reader, options)!;
  66. }
  67. /// <inheritdoc />
  68. public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options)
  69. {
  70. throw new NotImplementedException();
  71. }
  72. }
  73. }