ASP.NET Core2のStartup.csでJson.NETの設定を行う

ASP.NET CoreでJson.NET - Newtonsoftの設定をStartup.csに行うには以下の通りConfigureServicesで初期化を行うことができます。

public void ConfigureServices(IServiceCollection services)
        {
             ...
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            });
            ....
}

今回は値が設定されていない項目については出力しないように設定するようにしました。

なお、この設定は各フィールドに属性を以下の通り設定することでも対応できます。

[JsonProperty("property_name", NullValueHandling=NullValueHandling.Ignore)]
public string Hoge{get;set;}

ASP.NET MVCプログラミング入門 (マイクロソフト関連書)

ASP.NET MVCプログラミング入門 (マイクロソフト関連書)