CustomSerializer.cs 1.9 KB

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