将 C# 对象序列化为 JavaScript 对象表示法(JSON),默认情况下,将序列化所有公共属性。 如果不希望其中一些内容显示在生成的 JSON 中,可以使用多个选项。 本文介绍如何根据各种条件忽略属性:
忽略单个属性
若要忽略单个属性,请使用 [JsonIgnore] 属性。
以下示例演示要序列化的类型。 它还显示 JSON 输出:
public class WeatherForecastWithIgnoreAttribute
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
[JsonIgnore]
public string? Summary { get; set; }
}
Public Class WeatherForecastWithIgnoreAttribute
Public Property [Date] As DateTimeOffset
Public Property TemperatureCelsius As Integer
<JsonIgnore>
Public Property Summary As String
End Class
{
"Date": "2019-08-01T00:00:00-07:00",
"TemperatureCelsius": 25,
}
可以通过设置 [JsonIgnore] 属性 Condition
的属性来指定条件排除。
JsonIgnoreCondition枚举提供以下选项:
-
Always
- 始终忽略该属性。Condition
如果未指定,则假定此选项。 -
Never
- 无论全局设置DefaultIgnoreCondition
、IgnoreReadOnlyProperties
和IgnoreReadOnlyFields
如何,属性始终会被序列化和反序列化。 -
WhenWritingDefault
- 如果属性是引用类型、可以为 null 的值类型null
或值类型null
,则会在序列化时忽略该属性default
。 -
WhenWritingNull
- 如果属性是引用类型或可为 null 的值类型null
null
,则在序列化时忽略该属性。
以下示例演示如何使用 [JsonIgnore] 属性 Condition
:
using System.Text.Json;
using System.Text.Json.Serialization;
namespace JsonIgnoreAttributeExample
{
public class Forecast
{
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public DateTime Date { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.Never)]
public int TemperatureC { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? Summary { get; set; }
};
public class Program
{
public static void Run()
{
Forecast forecast = new()
{
Date = default,
Summary = null,
TemperatureC = default
};
JsonSerializerOptions options = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
};
string forecastJson =
JsonSerializer.Serialize<Forecast>(forecast,options);
Console.WriteLine(forecastJson);
}
}
}
// Produces output like the following example:
//
//{"TemperatureC":0}
Imports System.Text.Json
Imports System.Text.Json.Serialization
Namespace JsonIgnoreAttributeExample
Public Class Forecast
<JsonIgnore(Condition:=JsonIgnoreCondition.WhenWritingDefault)>
Public Property [Date] As Date
<JsonIgnore(Condition:=JsonIgnoreCondition.Never)>
Public Property TemperatureC As Integer
<JsonIgnore(Condition:=JsonIgnoreCondition.WhenWritingNull)>
Public Property Summary As String
End Class
Public NotInheritable Class Program
Public Shared Sub Main()
Dim forecast1 As New Forecast() With {
.[Date] = CType(Nothing, Date),
.Summary = Nothing,
.TemperatureC = CType(Nothing, Integer)
}
Dim options As New JsonSerializerOptions() With {
.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
}
Dim forecastJson As String = JsonSerializer.Serialize(forecast1, options)
Console.WriteLine(forecastJson)
End Sub
End Class
End Namespace
' Produces output like the following example:
'
'{"TemperatureC":0}
忽略所有只读属性
如果属性包含公共 getter 但不包含公共 setter,则属性为只读。 若要在序列化时忽略所有只读属性,请将其设置为JsonSerializerOptions.IgnoreReadOnlyPropertiestrue
,如以下示例所示:
var options = new JsonSerializerOptions
{
IgnoreReadOnlyProperties = true,
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(weatherForecast, options);
Dim options As JsonSerializerOptions = New JsonSerializerOptions With {
.IgnoreReadOnlyProperties = True,
.WriteIndented = True
}
jsonString = JsonSerializer.Serialize(weatherForecast, options)
以下示例演示要序列化的类型。 它还显示 JSON 输出:
public class WeatherForecastWithROProperty
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
public int WindSpeedReadOnly { get; private set; } = 35;
}
Public Class WeatherForecastWithROProperty
Public Property [Date] As DateTimeOffset
Public Property TemperatureCelsius As Integer
Public Property Summary As String
Private _windSpeedReadOnly As Integer
Public Property WindSpeedReadOnly As Integer
Get
Return _windSpeedReadOnly
End Get
Private Set(Value As Integer)
_windSpeedReadOnly = Value
End Set
End Property
End Class
{
"Date": "2019-08-01T00:00:00-07:00",
"TemperatureCelsius": 25,
"Summary": "Hot",
}
此选项仅适用于属性。 若要在 序列化字段时忽略只读字段,请使用 JsonSerializerOptions.IgnoreReadOnlyFields 全局设置。
注释
即使 JsonSerializerOptions.IgnoreReadOnlyProperties 设置为 true
,只读集合类型属性仍会被序列化。
忽略所有 null 值属性
若要忽略所有 null 值属性,请将 DefaultIgnoreCondition 该属性设置为 WhenWritingNull,如以下示例所示:
using System.Text.Json;
using System.Text.Json.Serialization;
namespace IgnoreNullOnSerialize
{
public class Forecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string? Summary { get; set; }
};
public class Program
{
public static void Run()
{
Forecast forecast = new()
{
Date = DateTime.Now,
Summary = null,
TemperatureC = default
};
JsonSerializerOptions options = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
string forecastJson =
JsonSerializer.Serialize<Forecast>(forecast, options);
Console.WriteLine(forecastJson);
}
}
}
// Produces output like the following example:
//
//{"Date":"2020-10-30T10:11:40.2359135-07:00","TemperatureC":0}
Imports System.Text.Json
Namespace IgnoreNullOnSerialize
Public Class Forecast
Public Property [Date] As Date
Public Property TemperatureC As Integer
Public Property Summary As String
End Class
Public NotInheritable Class Program
Public Shared Sub Main()
Dim forecast1 As New Forecast() With
{
.[Date] = Date.Now,
.Summary = Nothing,
.TemperatureC = CType(Nothing, Integer)
}
Dim options As New JsonSerializerOptions
Dim forecastJson As String = JsonSerializer.Serialize(forecast1, options)
Console.WriteLine(forecastJson)
End Sub
End Class
End Namespace
' Produces output like the following example:
'
'{"Date":"2020-10-30T10:11:40.2359135-07:00","TemperatureC":0}
忽略所有默认值属性
若要防止对值类型属性中的默认值进行序列化,请将 DefaultIgnoreCondition 该属性设置为 WhenWritingDefault,如以下示例所示:
using System.Text.Json;
using System.Text.Json.Serialization;
namespace IgnoreValueDefaultOnSerialize
{
public class Forecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string? Summary { get; set; }
};
public class Program
{
public static void Run()
{
Forecast forecast = new()
{
Date = DateTime.Now,
Summary = null,
TemperatureC = default
};
JsonSerializerOptions options = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
};
string forecastJson =
JsonSerializer.Serialize<Forecast>(forecast, options);
Console.WriteLine(forecastJson);
}
}
}
// Produces output like the following example:
//
//{ "Date":"2020-10-21T15:40:06.8920138-07:00"}
Imports System.Text.Json
Imports System.Text.Json.Serialization
Namespace IgnoreValueDefaultOnSerialize
Public Class Forecast
Public Property [Date] As Date
Public Property TemperatureC As Integer
Public Property Summary As String
End Class
Public NotInheritable Class Program
Public Shared Sub Main()
Dim forecast1 As New Forecast() With
{.[Date] = Date.Now,
.Summary = Nothing,
.TemperatureC = CType(Nothing, Integer)
}
Dim options As New JsonSerializerOptions() With {
.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
}
Dim forecastJson As String = JsonSerializer.Serialize(forecast1, options)
Console.WriteLine(forecastJson)
End Sub
End Class
End Namespace
' Produces output like the following example:
'
'{ "Date":"2020-10-21T15:40:06.8920138-07:00"}
该 WhenWritingDefault 设置还防止序列化 null 值引用类型和可以为 null 的值类型属性。