Created
November 9, 2012 05:11
-
-
Save mrchief/4043834 to your computer and use it in GitHub Desktop.
Swap ASP.NET WebAPI JsonFormatter with ServiceStack.Text JSON formatter
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 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