Skip to content

Instantly share code, notes, and snippets.

@rjygraham
Last active January 23, 2023 20:56
Show Gist options
  • Save rjygraham/85a8044c09e32554ef97c3d8c1238fb3 to your computer and use it in GitHub Desktop.
Save rjygraham/85a8044c09e32554ef97c3d8c1238fb3 to your computer and use it in GitHub Desktop.
NewtonsoftJsonCosmosSerializer
public CosmosClient CreateCosmosClient()
{
var jsonSerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
TypeNameHandling = TypeNameHandling.Auto,
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var cosmosOptions = new CosmosClientOptions
{
AllowBulkExecution = true,
EnableContentResponseOnWrite = false,
Serializer = new NewtonsoftJsonCosmosSerializer(jsonSerializerSettings)
};
return new CosmosClient("<your cosmos endpoint>", new DefaultAzureCredential(), cosmosOptions);
}
public abstract class EntityBase
{
public abstract string Version { get; }
}
public class PersonV1 : EntityBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override string Version { get; } = "V1";
}
public class PersonV2 : PersonV1
{
public DateTime Dob { get; set; }
public override string Version { get; } = "V2";
}
using Microsoft.Azure.Cosmos;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.IO;
using System.Text;
namespace Data.Storage;
/// <summary>
/// The default Cosmos JSON.NET serializer.
/// </summary>
internal sealed class NewtonsoftJsonCosmosSerializer : CosmosSerializer
{
private static readonly Encoding DefaultEncoding = new UTF8Encoding(false, true);
private readonly JsonSerializer Serializer;
/// <summary>
/// Create a serializer that uses the JSON.net serializer
/// </summary>
/// <remarks>
/// This is internal to reduce exposure of JSON.net types so
/// it is easier to convert to System.Text.Json
/// </remarks>
internal NewtonsoftJsonCosmosSerializer()
{
this.Serializer = JsonSerializer.Create();
}
/// <summary>
/// Create a serializer that uses the JSON.net serializer
/// </summary>
/// <remarks>
/// This is internal to reduce exposure of JSON.net types so
/// it is easier to convert to System.Text.Json
/// </remarks>
internal NewtonsoftJsonCosmosSerializer(CosmosSerializationOptions cosmosSerializerOptions)
{
JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
{
NullValueHandling = cosmosSerializerOptions.IgnoreNullValues ? NullValueHandling.Ignore : NullValueHandling.Include,
Formatting = cosmosSerializerOptions.Indented ? Formatting.Indented : Formatting.None,
ContractResolver = cosmosSerializerOptions.PropertyNamingPolicy == CosmosPropertyNamingPolicy.CamelCase
? new CamelCasePropertyNamesContractResolver()
: null,
TypeNameHandling = TypeNameHandling.Auto
};
this.Serializer = JsonSerializer.Create(jsonSerializerSettings);
}
/// <summary>
/// Create a serializer that uses the JSON.net serializer
/// </summary>
/// <remarks>
/// This is internal to reduce exposure of JSON.net types so
/// it is easier to convert to System.Text.Json
/// </remarks>
internal NewtonsoftJsonCosmosSerializer(JsonSerializerSettings jsonSerializerSettings)
{
this.Serializer = JsonSerializer.Create(jsonSerializerSettings);
}
/// <summary>
/// Convert a Stream to the passed in type.
/// </summary>
/// <typeparam name="T">The type of object that should be deserialized</typeparam>
/// <param name="stream">An open stream that is readable that contains JSON</param>
/// <returns>The object representing the deserialized stream</returns>
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 this.Serializer.Deserialize<T>(jsonTextReader);
}
}
}
}
/// <summary>
/// Converts an object to a open readable stream
/// </summary>
/// <typeparam name="T">The type of object being serialized</typeparam>
/// <param name="input">The object to be serialized</param>
/// <returns>An open readable stream containing the JSON of the serialized object</returns>
public override Stream ToStream<T>(T input)
{
MemoryStream streamPayload = new MemoryStream();
using (StreamWriter streamWriter = new StreamWriter(streamPayload, encoding: NewtonsoftJsonCosmosSerializer.DefaultEncoding, bufferSize: 1024, leaveOpen: true))
{
using (JsonWriter writer = new JsonTextWriter(streamWriter))
{
writer.Formatting = Formatting.None;
this.Serializer.Serialize(writer, input);
writer.Flush();
streamWriter.Flush();
}
}
streamPayload.Position = 0;
return streamPayload;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment