I have LoginModel:
public class LoginModel : IData
{
public string Email { get; set; }
public string Password { get; set; }
}
and I hav
To force all json data returned from api to camel case it's easier to use Newtonsoft Json with the default camel case contract resolver.
Create a class like this one:
using Newtonsoft.Json.Serialization;
internal class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
_jsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
return new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
}
}
and set this during api configuration (at startup):
var jsonFormatter = new JsonMediaTypeFormatter();
httpConfiguration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
If your are using Newtonsoft.Json, you can add JsonProperties to your view model :
public class LoginModel : IData
{
[JsonProperty(PropertyName = "email")]
public string Email {get;set;}
[JsonProperty(PropertyName = "password")]
public string Password {get;set;}
}
You can add the two following statement in the configuration of the web API or to the startup file
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
But it is very important to use the return Ok()
method instead of return Json()
otherwise; this will not work.
if you have to use Json method (and have no other choice) then see this answer https://stackoverflow.com/a/28960505/4390133
If you need it only in some certain place and not throughout whole application, then you can do following:
var objectToSerialize = new {Property1 = "value1", SubOjbect = new { SubObjectId = 1 }};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data, new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() });
It should result in {"property1":"value1","subOjbect":{"subObjectId":1}}
(note that nested properties also starts from lowercase)