Skip to content

Instantly share code, notes, and snippets.

@mrchief
Created November 9, 2012 05:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrchief/4043834 to your computer and use it in GitHub Desktop.
Save mrchief/4043834 to your computer and use it in GitHub Desktop.
Swap ASP.NET WebAPI JsonFormatter with ServiceStack.Text JSON formatter
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment