Return json with lowercase property names

I have a LoginModel:

public class LoginModel : IData { public string Email { get; set; } public string Password { get; set; } } 

and I have a web api method

 public IHttpActionResult Login([FromBody] LoginModel model) { return this.Ok(model); } 

And it returns 200 and body:

 { Email: "dfdf", Password: "dsfsdf" } 

But I want to get the bottom first letter in a type property

 { Email: "dfdf", Password: "dsfsdf" } 

And I have a Json contract resolver to fix

 public class FirstLowerContractResolver : DefaultContractResolver { protected override string ResolvePropertyName(string propertyName) { if (string.IsNullOrWhiteSpace(propertyName)) return string.Empty; return $"{char.ToLower(propertyName[0])}{propertyName.Substring(1)}"; } } 

How can i apply this?

+5
source share
3 answers

To force all json data returned from the api into the camel case, it is easier to use Newtonsoft Json with a standard camel resolver.

Create a class like this:

 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)); 
+7
source

If you 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;} } 
+6
source

You can add the following two statements in the web API configuration or in 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 return Ok() instead of return Json() , otherwise it will not work.

+1
source

All Articles