最佳答案
在 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; }
}
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; }
}
我在 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;
});
How can you set Camel Case serialize/deserialize in ASP.NET Core 3.0 using the new System.Text.Json namespace?
谢谢!