camelCase + indented JSON formatter for ASP.NET Web API
This file contains 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
... | |
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(); | |
... |
This file contains 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
// 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(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to apply this to odata?