Created
March 2, 2012 20:11
-
-
Save davidbitton/1960963 to your computer and use it in GitHub Desktop.
Using ServiceStack.Test JsonSerializer in a Web API MediaTypeFormatter
This file contains hidden or 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
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