Skip to content

Instantly share code, notes, and snippets.

@rdingwall
Created March 10, 2012 19:39
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rdingwall/2012642 to your computer and use it in GitHub Desktop.
Save rdingwall/2012642 to your computer and use it in GitHub Desktop.
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
Copy link

how to apply this to odata?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment