JsonDateTimeConverter.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. /// <summary>
  5. ///
  6. /// </summary>
  7. public class JsonDateTimeConverter : JsonConverter<DateTime>
  8. {
  9. private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff tt";
  10. /// <summary>
  11. /// Reads and converts the JSON to type.
  12. /// </summary>
  13. /// <param name="reader">The reader.</param>
  14. /// <param name="typeToConvert">The type to convert.</param>
  15. /// <param name="options">An object that specifies serialization options to use.</param>
  16. /// <returns>
  17. /// The converted value.
  18. /// </returns>
  19. /// <exception cref="System.Text.Json.JsonException">
  20. /// Unexpected token type: {reader.TokenType}
  21. /// or
  22. /// Unable to convert '{dateTimeString}' to DateTime
  23. /// </exception>
  24. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  25. {
  26. if (reader.TokenType != JsonTokenType.String)
  27. {
  28. throw new JsonException($"Unexpected token type: {reader.TokenType}");
  29. }
  30. string dateTimeString = reader.GetString();
  31. if (DateTime.TryParseExact(dateTimeString, DateTimeFormat, null, System.Globalization.DateTimeStyles.None, out DateTime dateTime))
  32. {
  33. return dateTime;
  34. }
  35. else
  36. {
  37. throw new JsonException($"Unable to convert '{dateTimeString}' to DateTime");
  38. }
  39. }
  40. /// <summary>
  41. /// Writes a specified value as JSON.
  42. /// </summary>
  43. /// <param name="writer">The writer to write to.</param>
  44. /// <param name="value">The value to convert to JSON.</param>
  45. /// <param name="options">An object that specifies serialization options to use.</param>
  46. public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
  47. {
  48. string dateTimeString = value.ToString(DateTimeFormat);
  49. writer.WriteStringValue(dateTimeString);
  50. }
  51. /// <summary>
  52. /// Determines whether the specified type can be converted.
  53. /// </summary>
  54. /// <param name="typeToConvert">The type to compare against.</param>
  55. /// <returns>
  56. /// <see langword="true" /> if the type can be converted; otherwise, <see langword="false" />.
  57. /// </returns>
  58. public override bool CanConvert(Type typeToConvert)
  59. {
  60. return typeToConvert == typeof(DateTime);
  61. }
  62. }