Using System.Text.Json for Camel Case Serialization
Use JsonPropertyName Attribute for Camel Case Serialization
public class PersonWithAttributes
{
[JsonPropertyName("firstName")]
public string? FirstName { get; set; }
[JsonPropertyName("surname")]
public string? Surname { get; set; }
[JsonPropertyName("age")]
public int? Age { get; set; }
[JsonPropertyName("isActive")]
public bool? IsActive { get; set; }
}
Create JsonSerializerExtensions
public static class JsonSerializerExtensions
{
public static string SerializeWithCamelCase<T>(this T data)
{
return JsonSerializer.Serialize(data, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
}
public static T DeserializeFromCamelCase<T>(this string json)
{
return JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
}
}
How to use ?
var personWithAttributes = new PersonWithAttributes
{
Age = 20,
FirstName = "John",
Surname = "Doe",
IsActive = true
};
JsonSerializer.Serialize(personWithAttributes, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
or
personWithAttributes.SerializeWithCamelCase();
or
personWithAttributes.DeserializeFromCamelCase<PersonWithAttributes>()