Created
July 16, 2019 22:21
-
-
Save richstokoe/c82fc831c6b4020926f5b5f772f7cd70 to your computer and use it in GitHub Desktop.
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; | |
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
The constructor that takes JsonSerializerSettings on that is internal.