JsonGuidConverter.cs 910 B

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