JsonNullableGuidConverter.cs 1009 B

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. using System.Globalization;
  3. using System.Text.Json;
  4. using System.Text.Json.Serialization;
  5. namespace MediaBrowser.Common.Json.Converters
  6. {
  7. /// <summary>
  8. /// Converts a GUID object or value to/from JSON.
  9. /// </summary>
  10. public class JsonNullableGuidConverter : JsonConverter<Guid?>
  11. {
  12. /// <inheritdoc />
  13. public override Guid? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  14. {
  15. var guidStr = reader.GetString();
  16. return guidStr == null ? null : new Guid(guidStr);
  17. }
  18. /// <inheritdoc />
  19. public override void Write(Utf8JsonWriter writer, Guid? value, JsonSerializerOptions options)
  20. {
  21. if (value == null || value == Guid.Empty)
  22. {
  23. writer.WriteNullValue();
  24. }
  25. else
  26. {
  27. writer.WriteStringValue(value.Value.ToString("N", CultureInfo.InvariantCulture));
  28. }
  29. }
  30. }
  31. }