ASP.NET Core 3.0 System.Text.Json キャメルケースシリアル化 質問する

ASP.NET Core 3.0 System.Text.Json キャメルケースシリアル化 質問する

ASP.NET Core 3.0 Web APIプロジェクトでは、どのように指定しますか?システム.テキスト.JsonPascal Case プロパティを Camel Case に、またはその逆に自動的にシリアル化/逆シリアル化するシリアル化オプションはありますか?

次のような Pascal Case プロパティを持つモデルがあるとします。

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

System.Text.Json を使用して JSON 文字列をクラスの型に逆シリアル化するコードPerson:

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

次の場合を除き、デシリアライズは成功しません。Jsonプロパティ名次のように各プロパティで使用されます。

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 のシリアル化/逆シリアル化を設定するにはどうすればよいですか?

ありがとう!

ベストアンサー1

AddJsonOptions()System.Text.JsonMVC のみの設定になります。JsonSerializer独自のコードで使用する場合は、その設定を渡す必要があります。

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

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

おすすめ記事