Created
August 8, 2018 03:42
-
-
Save andy-uq/c5964f69bb442c79562f3259ab4f7a94 to your computer and use it in GitHub Desktop.
A class for serialising content with a custom JSON serialiser
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
public class JsonContent : HttpContent | |
{ | |
private static readonly JsonSerializer s_defaultDecisionEngineJsonSerialiser = JsonSerializer.Create(new DecisionEngineJsonSerializerSettings()); | |
private readonly Lazy<JsonSerializer> _serialiser; | |
private readonly object _value; | |
public Encoding Encoding { get; } | |
public JsonContent(object value) | |
{ | |
_value = value; | |
_serialiser = new Lazy<JsonSerializer>(CreateJsonSerialiser); | |
Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); | |
Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = Encoding.WebName }; | |
} | |
protected virtual JsonSerializer CreateJsonSerialiser() | |
{ | |
return s_defaultDecisionEngineJsonSerialiser; | |
} | |
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) | |
{ | |
using (var writer = new JsonTextWriter(new StreamWriter(stream, Encoding, bufferSize: 4096, leaveOpen: true))) | |
{ | |
await JObject | |
.FromObject(_value, _serialiser.Value) | |
.WriteToAsync(writer); | |
} | |
} | |
protected override bool TryComputeLength(out long length) | |
{ | |
length = -1; | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment