Return json with lower case first letter of property names

camelcasenamingstrategy
pascal case in json
json dynamic property name c#
c# deserialize json lowercase
camelcasepropertynamescontractresolver
json camelcase
datacontractjsonserializer camelcase
jsonconvert serializeobject lower case

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?

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

JsonResult converts uppercase property names to lowercase · Issue , My Model Gender.cs and my Controller use an uppercase property name. When the JsonResult converts uppercase property names to lowercase #5046. Closed GenderList.Add(gender); } return Json(GenderList); }  Unfortunately as far as I can tell once you've used JsonSerializer.Deserialize( ) (non-generic version) and hence created a JObject, the only way to then override the property names is to declare your own Json(Text)Writer class that overrides WritePropertyName( ), and there's no way of configuring JsonConvert.Serialize( ) to use a custom JsonWriter class.

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;}
}

ASP.NET Web Api - Setup JSON Camel Cased Fields, NET Web Api project, created our 1st controller and enabled Windows authentication. In this article we will learn how to set the JSON response to convert the . JSON uses camel case which means that the property names start with a lowercase letter and then each word after that starts with a captial letter  My Model Gender.cs and my Controller use an uppercase property name. When the JsonResult data is sent back to the Angular 2 RC4 view it is converted into lowercase: GenderName and GenderId change to genderName and genderId. Even Intellisense in my TypeScript file uses GenderName

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() or this is will not work.

Serializing a PascalCase Newtonsoft.Json JObject to camelCase, In this post I describe one of the quirks of serializing a JSON. serializing a JObject that stored its property names in PascalCase. In this case, the JObject was a "serialized" version of a data class: Lets start by seeing what you get if you Serialize the dog instance above, by returning it from an ASP. Without changing the underlying stored procedures, I would simply like to have my service change the field names in the JSON result to be all lower case. What would be the easiest way to do this without having to repeat this in every method cotnained in my service?

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)

Camel case property names, This sample uses a T:Newtonsoft.Json.Serialization.CamelCaseNamingStrategy specified using a contract resolver to camel case serialized property names. In previous milestones, MVC's JSON serialization used Json.NET's default naming convention. This maintained C# property names in the JSON. In 1.0.0, MVC uses camel case names by default. This matches most JSON naming conventions. Potential compatibility breaks. Applications which depend on the exact bytes sent over the wire or that include code

How to get the JSON fields in all lowercase, Core service that returns data directly from SQL Server as a JSON. the column names are mixed in lower/upper cases and this makes it  JSON properties now lower case on swap from ASP .Net Core 1.0.0-rc2-final to 1.0.0. I've just swapped our project from ASP .Net Core 1.0.0-rc2-final to 1.0.0. Our website and client have stopped working because of the capitalization of JSON properties.

Json key camel or snake, First, we initialize a variable 'res' with an empty list and append first character (in lower case) to it. typical camel case Java property names to lower case JSON element names, NET objects to JSON returns the properties PascalCase. Configure NamingStrategy property name serialization Camel case property names This sample uses a CamelCaseNamingStrategy specified using a contract resolver to camel case serialized property names.

JSON, The first character must be a letter, an underscore (_) or a dollar sign ($). The property name naming rules do not apply when a JSON object is used as a map. A map In the case of a JSON response, the method property can indicate the  How can I configure serialization of my Web API to use camelCase (starting from lowercase letter) property names instead of PascalCase like it is in C#. Can I do it globally for the whole project? c# .net asp.net-mvc asp.net-web-api json.net

Comments
  • Will this work? tostring.it/2012/07/18/customize-json-result-in-web-api
  • This works very well even with Entity Framework in a WebAPI project. Just place the startup code provided here in the WebApiConfig class (replace httpConfiguration with config).
  • There is only one issue, all the json fields, also the ones not related to the viewmodel, are going to be lower cased. The other issue is that it does not work with nested properties/objects ie: myTopKey.MySubKey --should be---> myTopKey.mySubKey
  • I need this style, thanks a lot
  • So much better than accepted answer! But, I am only going to use CamelCasePropertyNamesContractResolver; not Formatting.Indented