Search code examples
c#jsonasp.net-web-api

Return json with lower case first letter of property names


I have LoginModel:

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

and I have the Web api method

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

And it's return 200 and body:

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

But I want to get with lower first letter in property like

{
    email: "dfdf",
    password: "dsfsdf"
}

And I have Json contract resolver for correcting

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 I can apply this?


Solution

  • 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));