Skip to content

Instantly share code, notes, and snippets.

@andy-uq
Created August 8, 2018 03:42
Show Gist options
  • Save andy-uq/c5964f69bb442c79562f3259ab4f7a94 to your computer and use it in GitHub Desktop.
Save andy-uq/c5964f69bb442c79562f3259ab4f7a94 to your computer and use it in GitHub Desktop.
A class for serialising content with a custom JSON serialiser
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