public
Last active

Swap ASP.NET WebAPI JsonFormatter with ServiceStack.Text JSON formatter

  • Download Gist
ServiceStackJsonFormatter.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
public class ServiceStackJsonFormatter : MediaTypeFormatter
{
public ServiceStackJsonFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
SupportedEncodings.Add(new UTF8Encoding(false, true));
SupportedEncodings.Add(new UnicodeEncoding(false, true, true));
}
 
#region Overrides of MediaTypeFormatter
 
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
{
return Task.Factory.StartNew(() =>
{
var result = JsonSerializer.DeserializeFromStream(type, readStream);
return result;
});
}
 
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
{
return Task.Factory.StartNew(() => JsonSerializer.SerializeToStream(value, type, writeStream));
}
 
/// <summary>
/// Queries whether this <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> can deserializean object of the specified type.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> can deserialize the type; otherwise, false.
/// </returns>
/// <param name="type">The type to deserialize.</param>
public override bool CanReadType(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
 
return true;
}
 
/// <summary>
/// Queries whether this <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> can serializean object of the specified type.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> can serialize the type; otherwise, false.
/// </returns>
/// <param name="type">The type to serialize.</param>
public override bool CanWriteType(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
 
return true;
}
 
#endregion
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.