In ASP.NET Core 3.0 Web API project, how do you specify System.Text.Json serialization options to serialize/deserialize Pascal Case properties to Camel Case and vice versa automatically?
Given a model with Pascal Case properties such as:
public class Person
{
public string Firstname { get; set; }
public string Lastname { get; set; }
}
And code to use System.Text.Json to deserialize a JSON string to type of Person
class:
var json = "{\"firstname\":\"John\",\"lastname\":\"Smith\"}";
var person = JsonSerializer.Deserialize<Person>(json);
Does not successfully deserialize unless JsonPropertyName is used with each property like:
public class Person
{
[JsonPropertyName("firstname")]
public string Firstname { get; set; }
[JsonPropertyName("lastname")]
public string Lastname { get; set; }
}
I tried the following in startup.cs
, but it did not help in terms of still needing JsonPropertyName
:
services.AddMvc().AddJsonOptions(options =>
{
options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
// also the following given it's a Web API project
services.AddControllers().AddJsonOptions(options => {
options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
How can you set Camel Case serialize/deserialize in ASP.NET Core 3.0 using the new System.Text.Json namespace?
Thanks!