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

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

问题描述

在ASP.NET Core 3.0 Web API项目中,如何指定

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

除非

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案例序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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