Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
camelCase + indented JSON formatter for ASP.NET Web API
...
var config = GlobalConfiguration.Configuration;
// Replace the default JsonFormatter with our custom one
var index = config.Formatters.IndexOf(config.Formatters.JsonFormatter);
config.Formatters[index] = new JsonCamelCaseFormatter();
...
// Originally from http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net-with-asp-net-web-api.aspx
public class JsonCamelCaseFormatter : MediaTypeFormatter
{
private readonly JsonSerializerSettings jsonSerializerSettings;
public JsonCamelCaseFormatter()
{
jsonSerializerSettings =
new JsonSerializerSettings
{
ContractResolver =
new CamelCasePropertyNamesContractResolver()
};
// Fill out the mediatype and encoding we support
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
Encoding = new UTF8Encoding(false, true);
}
protected override bool CanReadType(Type type)
{
return type != typeof (IKeyValueModel);
}
protected override bool CanWriteType(Type type)
{
return true;
}
protected override Task<object> OnReadFromStreamAsync(Type type,
Stream stream, HttpContentHeaders contentHeaders,
FormatterContext formatterContext)
{
// Create a serializer
var serializer = JsonSerializer.Create(jsonSerializerSettings);
// Create task reading the content
return Task.Factory.StartNew(
() =>
{
using (var streamReader = new StreamReader(stream, Encoding))
using (var jsonTextReader = new JsonTextReader(streamReader))
return serializer.Deserialize(jsonTextReader, type);
});
}
protected override Task OnWriteToStreamAsync(Type type, object value,
Stream stream, HttpContentHeaders contentHeaders,
FormatterContext formatterContext,
TransportContext transportContext)
{
// Create a serializer
var serializer = JsonSerializer.Create(jsonSerializerSettings);
// Create task writing the serialized content
return Task.Factory.StartNew(
() =>
{
using (var jsonTextWriter =
new JsonTextWriter(new StreamWriter(stream, Encoding))
{
Formatting = Formatting.Indented,
CloseOutput = false
})
{
serializer.Serialize(jsonTextWriter, value);
jsonTextWriter.Flush();
}
});
}
}
@tshwangq

This comment has been minimized.

Copy link

commented Apr 27, 2013

how to apply this to odata?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.