ASP.NET Core 3.0 System.Text.Json Camel Case 序列化 [英] ASP.NET Core 3.0 System.Text.Json Camel Case Serialization

查看:43
本文介绍了ASP.NET Core 3.0 System.Text.Json Camel Case 序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ASP.NET Core 3.0 Web API 项目中,如何指定 System.Text.Json 序列化选项,用于自动将 Pascal Case 属性序列化/反序列化为 Camel Case,反之亦然?

In ASP.NET Core 3.0 Web API project, how do you specify System.Text.Json serialization options to serialize/deserialize Pascal Case properties to Camel Case and vice versa automatically?

给定一个具有 Pascal Case 属性的模型,例如:

Given a model with Pascal Case properties such as:

public class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

以及使用 System.Text.Json 将 JSON 字符串反序列化为 Person 类类型的代码:

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);

不会成功反序列化,除非 JsonPropertyName 与每个属性一起使用,例如:

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 方面没有帮助:

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;
        });

如何使用新的 System.Text.Json 命名空间在 ASP.NET Core 3.0 中设置 Camel Case 序列化/反序列化?

How can you set Camel Case serialize/deserialize in ASP.NET Core 3.0 using the new System.Text.Json namespace?

谢谢!

推荐答案

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

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);

这篇关于ASP.NET Core 3.0 System.Text.Json Camel Case 序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆