在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!

推荐答案

AddJsonOptions() would config System.Text.Json only for MVC. If you want to use JsonSerializer in your own code you should pass the config to it.

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

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

Json相关问答推荐

JOLT转换,将属性复制到同级别的dict中

使用Shell深入挖掘到最低的SON元素

盒子图显示不正确

Allof Indide的JSON模式之一

419(未知状态)使用laravel处理PUT请求

ETCD 导出为 json 并从 base64 解码所有键/值到人类可读

在 CodePipeline 中调用 lambda 时传递用户参数

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

为什么根据其他工具,来自 aws rds 的 JSON 在 Docker 中格式错误运行?

下一个 Js 部署在 getStaticPath 函数上失败:在 JSON.parse 的位置 0 的 JSON 中出现意外的令牌 < 但在本地运行

在循环中将变量添加到 bash 数组

从 json 对象中过滤掉所有出现的给定属性

如何使用法语口音对数组进行 json_encode?

jQuery AJAX 和 JSON 格式

Jsonpath 与 Jackson 或 Gson

Spring Security 和 JSON 身份验证

使用 Node.js 对 JSON 中的字符串大小有限制吗?

无法将空值放入 JSON 对象

Microsoft.Net.Http 与 Microsoft.AspNet.WebApi.Client

运算符不存在:json = json