在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; }
}
以及使用System.Text.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; }
}
我在中尝试了以下方法startup.cs
,但在仍然需要方面没有帮助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;
});
如何使用新的System.Text.Json命名空间在ASP.NET Core 3.0中设置Camel Case序列化/反序列化?
谢谢!