在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类类型的代码:
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:
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序列化/反序列化?
谢谢!
AddJsonOptions()将System.Text.Json仅配置为MVC。如果要JsonSerializer在自己的代码中使用,则应将配置传递给它。
AddJsonOptions()
System.Text.Json
JsonSerializer
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; var json = "{\"firstname\":\"John\",\"lastname\":\"Smith\"}"; var person = JsonSerializer.Parse<Person>(json, options);