Forked from richstokoe/JSON.NET Serializer for Cosmos dotnet SDK v3
Created
October 17, 2019 00:43
-
-
Save shanerogers/adade76f273101b8774a0984fdadfbf2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment