Skip to content

Instantly share code, notes, and snippets.

@davidbitton
Created March 2, 2012 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidbitton/1960963 to your computer and use it in GitHub Desktop.
Save davidbitton/1960963 to your computer and use it in GitHub Desktop.
Using ServiceStack.Test JsonSerializer in a Web API MediaTypeFormatter
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Text;
namespace HttpClientTest.Formatters {
public class ServiceStackFormatter : MediaTypeFormatter {
public ServiceStackFormatter() {
// Fill out the mediatype and encoding we support
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
Encoding = new UTF8Encoding(false, true);
}
protected override bool CanReadType(System.Type type) {
return type != typeof(IKeyValueModel);
}
protected override bool CanWriteType(System.Type type) {
return true;
}
protected override Task<object> OnReadFromStreamAsync(System.Type type, System.IO.Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext) {
return Task.Factory.StartNew(() => JsonSerializer.DeserializeFromStream(type, stream));
}
protected override Task OnWriteToStreamAsync(System.Type type, object value, System.IO.Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, System.Net.TransportContext transportContext) {
return Task.Factory.StartNew(() => JsonSerializer.SerializeToStream(value, type, stream));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment