Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 305
MihailPw Avatar asked Apr 27 '16 08:04

MihailPw


People also ask

Should JSON properties be LowerCase?

property names must start with lower case letter. Dictionary must be serialized into jsonp where keys will be used for property names. LowerCase rule does not apply for dictionary keys.

What is JSON property name?

The Jackson Annotation @JsonProperty is used on a property or method during serialization or deserialization of JSON. It takes an optional 'name' parameter which is useful in case the property name is different than 'key' name in JSON.

What is JSON property in C#?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.


3 Answers

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;} } 
like image 129
AdrienTorris Avatar answered Sep 17 '22 22:09

AdrienTorris


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)); 
like image 23
Luca Ghersi Avatar answered Sep 18 '22 22:09

Luca Ghersi


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

like image 32
Hakan Fıstık Avatar answered Sep 16 '22 22:09

Hakan Fıstık