SystemTextJsonCosmosSerializer.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using Microsoft.Azure.Cosmos;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.IO;
  6. using System.Text;
  7. using System.Text.Json;
  8. namespace CosmosDB3Test
  9. {
  10. internal sealed class SystemTextJsonCosmosSerializer : CosmosSerializer
  11. {
  12. private readonly JsonSerializerOptions _options;
  13. internal SystemTextJsonCosmosSerializer(JsonSerializerOptions options)
  14. {
  15. _options = options;
  16. }
  17. /// <inheritdoc />
  18. public override T FromStream<T>(Stream stream)
  19. {
  20. // Have to dispose of the stream, otherwise the Cosmos SDK throws.
  21. // https://github.com/Azure/azure-cosmos-dotnet-v3/blob/0843cae3c252dd49aa8e392623d7eaaed7eb712b/Microsoft.Azure.Cosmos/src/Serializer/CosmosJsonSerializerWrapper.cs#L22
  22. // https://github.com/Azure/azure-cosmos-dotnet-v3/blob/0843cae3c252dd49aa8e392623d7eaaed7eb712b/Microsoft.Azure.Cosmos/src/Serializer/CosmosJsonDotNetSerializer.cs#L73
  23. using (stream)
  24. {
  25. // TODO Would be more efficient if CosmosSerializer supported async
  26. // See https://github.com/Azure/azure-cosmos-dotnet-v3/issues/715
  27. using var memory = new MemoryStream((int)stream.Length);
  28. stream.CopyTo(memory);
  29. byte[] utf8Json = memory.ToArray();
  30. return JsonSerializer.Deserialize<T>(utf8Json, _options);
  31. }
  32. }
  33. /// <inheritdoc />
  34. public override Stream ToStream<T>(T input)
  35. {
  36. byte[] utf8Json = JsonSerializer.SerializeToUtf8Bytes(input, _options);
  37. return new MemoryStream(utf8Json);
  38. }
  39. }
  40. }