在ASP.NET Core 3.0 Web API项目,如何指定System.Text.Json个序列化选项来将Pascal Case属性序列化/反序列化为Camel Case,反之亦然?
给定一个具有PASCAL case 属性的模型,例如:
public class Person
{
public string Firstname { get; set; }
public string Lastname { get; set; }
}
以及使用系统的代码.文本Json将Json字符串反序列化为Person
类:
var json = "{\"firstname\":\"John\",\"lastname\":\"Smith\"}";
var person = JsonSerializer.Deserialize<Person>(json);
除非JsonPropertyName与每个属性一起使用,否则无法成功反序列化,例如:
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!