Skip to content

Instantly share code, notes, and snippets.

@ahmettek
Created March 7, 2015 23:17
Show Gist options
  • Save ahmettek/038892314303700c8308 to your computer and use it in GitHub Desktop.
Save ahmettek/038892314303700c8308 to your computer and use it in GitHub Desktop.
Custom MediaTypeFormatter - Web Api JsonNetFormatter
public class JsonNetFormatter : MediaTypeFormatter
{
public JsonNetFormatter()
{
SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
}
public override bool CanWriteType(Type type)
{
// don't serialize JsonValue structure use default for that
if (type == typeof(JValue) || type == typeof(JObject) || type == typeof(JArray))
return false;
return true;
}
public override bool CanReadType(Type type)
{
return true;
}
public override System.Threading.Tasks.Task<object> ReadFromStreamAsync(Type type,
Stream stream,
HttpContent content,
IFormatterLogger formatterLogger)
{
var task = Task<object>.Factory.StartNew(() =>
{
var settings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
};
var sr = new StreamReader(stream);
var jreader = new JsonTextReader(sr);
var ser = new JsonSerializer();
ser.Converters.Add(new IsoDateTimeConverter());
object val = ser.Deserialize(jreader, type);
return val;
});
return task;
}
public override Task WriteToStreamAsync(Type type, object value,
Stream stream,
HttpContent content,
TransportContext transportContext)
{
var task = Task.Factory.StartNew( () =>
{
var settings = new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
};
string json = JsonConvert.SerializeObject(value, Formatting.Indented,
new JsonConverter[1] { new IsoDateTimeConverter() } );
byte[] buf = System.Text.Encoding.Default.GetBytes(json);
stream.Write(buf,0,buf.Length);
stream.Flush();
});
return task;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment