如何使用 System.Text.Json 启用不区分大小写的属性名称

本文将介绍如何使用 System.Text.Json 命名空间启用不区分大小写的属性名称匹配。

不区分大小写的属性匹配

默认情况下,反序列化会查找 JSON 与目标对象属性之间区分大小写的属性名称匹配。 若要更改该行为,请将 JsonSerializerOptions.PropertyNameCaseInsensitive 设置为 true

注意

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)

下面是具有 camel 大小写属性名称的示例 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

请参阅