System.Text.Json で大文字と小文字を区別しないプロパティ名の照合を有効にする方法

この記事では、System.Text.Json 名前空間を使用して、大文字と小文字を区別しないプロパティ名の照合を有効にする方法について説明します。

大文字と小文字を区別しないプロパティ照合

既定では、逆シリアル化では JSON とターゲット オブジェクトのプロパティとの間で大文字と小文字を区別したプロパティ名の一致が検索されます。 この動作を変更するには、JsonSerializerOptions.PropertyNameCaseInsensitivetrue に設定します。

Note

Web の既定値では大文字と小文字が区別されません。

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};
WeatherForecast? weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString, options);
Dim options As JsonSerializerOptions = New JsonSerializerOptions With {
    .PropertyNameCaseInsensitive = True
}
Dim weatherForecast1 = JsonSerializer.Deserialize(Of WeatherForecast)(jsonString, options)

キャメル ケースのプロパティ名を持つ JSON の例を次に示します。 これはパスカル ケースのプロパティ名を持つ次の型に逆シリアル化できます。

{
  "date": "2019-08-01T00:00:00-07:00",
  "temperatureCelsius": 25,
  "summary": "Hot",
}
public class WeatherForecast
{
    public DateTimeOffset Date { get; set; }
    public int TemperatureCelsius { get; set; }
    public string? Summary { get; set; }
}
Public Class WeatherForecast
    Public Property [Date] As DateTimeOffset
    Public Property TemperatureCelsius As Integer
    Public Property Summary As String
End Class

関連項目