c# - ASP.NET Core 3.0 System.Text.Json Camel Case 序列化

标签 c# json asp.net-core system.text.json

在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 类型的代码类(class):
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 序列化/反序列化?
谢谢!

最佳答案

AddJsonOptions()将配置 System.Text.Json仅适用于 MVC。如果您想使用 JsonSerializer在您自己的代码中,您应该将配置传递给它。

var options = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};

var json = "{\"firstname\":\"John\",\"lastname\":\"Smith\"}";
var person = JsonSerializer.Parse<Person>(json, options);

关于c# - ASP.NET Core 3.0 System.Text.Json Camel Case 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58476681/

相关文章:

c# - 将对象转换为 JSON,然后将该 JSON 下载为文本文件 [Asp.net core]

asp.net-web-api - 枚举值不解析时如何将枚举作为字符串绑定(bind)失败处理

C# - LinkedList - 如何删除指定节点之后的所有节点?

python - SQLAlchemy:过滤存储在 JSONB 字段的嵌套列表中的值

jquery - 如何使用JQuery在下拉列表中选择默认值

java - 如何使用 Java 解析从 android 中的 facebook 检索到的 JSONObject?

dependency-injection - 在 IServiceProvider 上,GetRequiredService 和 GetService 方法有什么区别?

c# - System.Timers.Timer 稳步增加间隔

c# - 正确使用 Entity Framework 事务进行隔离

c# - 将程序锁定到它运行的第一台计算机?