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?
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.
Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
If you want to change serialization behavior in Newtonsoft.Json aka JSON.NET, you need to create your settings:
var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore // ignore null values });
You can also pass these settings into JsonConvert.SerializeObject
:
JsonConvert.SerializeObject(objectToSerialize, serializerSettings);
protected void Application_Start() { GlobalConfiguration.Configuration .Formatters .JsonFormatter .SerializerSettings .ContractResolver = new CamelCasePropertyNamesContractResolver(); }
Exclude null values:
GlobalConfiguration.Configuration .Formatters .JsonFormatter .SerializerSettings .NullValueHandling = NullValueHandling.Ignore;
Indicates that null values should not be included in resulting JSON.
ASP.NET Core by default serializes values in camelCase format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With