Last active
June 19, 2021 22:29
-
-
Save ankitvijay/3946e9c807dd21306b19a9c42b85821e to your computer and use it in GitHub Desktop.
Cosmos DB System.Text.Json Serializier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Text.Json; | |
using Azure.Core.Serialization; | |
using Microsoft.Azure.Cosmos; | |
/// <remarks> | |
// See: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/SystemTextJson/CosmosSystemTextJsonSerializer.cs | |
/// </remarks> | |
public sealed class CosmosSystemTextJsonSerializer : CosmosSerializer | |
{ | |
private readonly JsonObjectSerializer _systemTextJsonSerializer; | |
public CosmosSystemTextJsonSerializer(JsonSerializerOptions jsonSerializerOptions) | |
{ | |
_systemTextJsonSerializer = new JsonObjectSerializer(jsonSerializerOptions); | |
} | |
public override T FromStream<T>(Stream stream) | |
{ | |
if (stream.CanSeek && stream.Length == 0) | |
{ | |
return default; | |
} | |
if (typeof(Stream).IsAssignableFrom(typeof(T))) | |
{ | |
return (T) (object) stream; | |
} | |
using (stream) | |
{ | |
return (T) _systemTextJsonSerializer.Deserialize(stream, typeof(T), default); | |
} | |
} | |
public override Stream ToStream<T>(T input) | |
{ | |
var streamPayload = new MemoryStream(); | |
_systemTextJsonSerializer.Serialize(streamPayload, input, typeof(T), default); | |
streamPayload.Position = 0; | |
return streamPayload; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment