I’m currently facing difficulties in converting object properties to lower camel case using Newtonsoft JSON serialization in C#. Here’s a simplified version of the code I’m using:
[JsonObject(Title = "booking")]
public class BookingJsonModel
{
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("reference")]
public string Reference { get; set; } = null!;
//...
}
and I have also tried to declare a property:
[JsonProperty(PropertyName = "reference")]
public string Reference { get; set; } = null!;
During serialization, I’m attempting to convert property names to lower camel case using the following code:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
string body = JsonConvert.SerializeObject(data, settings);
Despite setting the ContractResolver to CamelCasePropertyNamesContractResolver()
, the properties remain unchanged and still start with an upper case letter. It seems like both the ContractResolver and JsonProperty attributes are being ignored during serialization.
Could someone provide guidance or suggest an alternative approach to ensure the serialization of object properties to lower camel case using Newtonsoft JSON library in C#? Any insights or resolutions to this issue would be greatly appreciated. Thank you!
2
Answers
The
maps the property name in the raw JSON string, "some name" to the SomeName property in your class definition.
If you have defined your class to use the Property name "SomeName" the upper case on your model is what JSON maps the string INTO.
if you want your own model to have lower case words, simply define your model as such.
so it becomes
This however violates normal naming convention that states Properties should start with upper case letters.
or, use the
Annotation instead, that should actually resolve what you want.
If you’re using Newtonsoft.Json in C# and want to convert property names to lower camel case (e.g., myProperty instead of MyProperty), you can achieve this by configuring the JsonSerializerSettings with the ContractResolver property.
Here’s an example of how to configure Newtonsoft.Json to serialize objects with lower camel case property names:
See the reference output