Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save richstokoe/c82fc831c6b4020926f5b5f772f7cd70 to your computer and use it in GitHub Desktop.
Save richstokoe/c82fc831c6b4020926f5b5f772f7cd70 to your computer and use it in GitHub Desktop.
using System.IO;
using System.Text;
using Microsoft.Azure.Cosmos;
using Newtonsoft.Json;
namespace Application1
{
public class CosmosJsonNetSerializer : CosmosSerializer
{
private static readonly Encoding DefaultEncoding = new UTF8Encoding(false, true);
private readonly JsonSerializer Serializer;
private readonly JsonSerializerSettings serializerSettings;
public CosmosJsonNetSerializer()
: this(new JsonSerializerSettings())
{
}
public CosmosJsonNetSerializer(
JsonSerializerSettings serializerSettings
)
{
this.serializerSettings = serializerSettings;
this.Serializer = JsonSerializer.Create(this.serializerSettings);
}
public override T FromStream<T>(Stream stream)
{
using (stream)
{
if (typeof(Stream).IsAssignableFrom(typeof(T)))
{
return (T)(object)(stream);
}
using (StreamReader sr = new StreamReader(stream))
{
using (JsonTextReader jsonTextReader = new JsonTextReader(sr))
{
return Serializer.Deserialize<T>(jsonTextReader);
}
}
}
}
public override Stream ToStream<T>(T input)
{
MemoryStream streamPayload = new MemoryStream();
using (StreamWriter streamWriter = new StreamWriter(streamPayload, encoding: DefaultEncoding, bufferSize: 1024, leaveOpen: true))
{
using (JsonWriter writer = new JsonTextWriter(streamWriter))
{
writer.Formatting = Newtonsoft.Json.Formatting.None;
Serializer.Serialize(writer, input);
writer.Flush();
streamWriter.Flush();
}
}
streamPayload.Position = 0;
return streamPayload;
}
}
}
@GrimGadget
Copy link

There's also this official one: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos/src/Serializer/CosmosJsonDotNetSerializer.cs

The constructor that takes JsonSerializerSettings on that is internal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment