Como ignorar Propriedades com System.Text.JsonHow to ignore properties with System.Text.Json
Ao serializar objetos C# para JavaScript Object Notation (JSON), por padrão, todas as propriedades públicas são serializadas.When serializing C# objects to JavaScript Object Notation (JSON), by default, all public properties are serialized. Se não quiser que algumas delas apareçam no JSON resultante, você terá várias opções.If you don't want some of them to appear in the resulting JSON, you have several options. Neste artigo, você aprenderá a ignorar Propriedades com base em vários critérios:In this article you learn how to ignore properties based on various criteria:
Ignorar propriedades individuaisIgnore individual properties
Para ignorar as propriedades individuais, use o atributo [JsonIgnore] .To ignore individual properties, use the [JsonIgnore] attribute.
Aqui está um tipo de exemplo para serializar e a saída JSON:Here's an example type to serialize and JSON output:
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,
}
Você pode especificar a exclusão condicional definindo a propriedade do atributo [JsonIgnore] Condition
.You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition
property. A JsonIgnoreCondition enumeração fornece as seguintes opções:The JsonIgnoreCondition enum provides the following options:
Always
-A propriedade é sempre ignorada.Always
- The property is always ignored. Se nãoCondition
for especificado, essa opção será assumida.If noCondition
is specified, this option is assumed.Never
-A propriedade é sempre serializada e desserializada, independentemente dasDefaultIgnoreCondition
IgnoreReadOnlyProperties
IgnoreReadOnlyFields
configurações globais, e.Never
- The property is always serialized and deserialized, regardless of theDefaultIgnoreCondition
,IgnoreReadOnlyProperties
, andIgnoreReadOnlyFields
global settings.WhenWritingDefault
-A propriedade será ignorada na serialização se for um tipo de referêncianull
, um tipo de valor Anulávelnull
ou um tipo de valordefault
.WhenWritingDefault
- The property is ignored on serialization if it's a reference typenull
, a nullable value typenull
, or a value typedefault
.WhenWritingNull
-A propriedade será ignorada na serialização se for um tipo de referêncianull
ou um tipo de valor Anulávelnull
.WhenWritingNull
- The property is ignored on serialization if it's a reference typenull
, or a nullable value typenull
.
O exemplo a seguir ilustra o uso da Propriedade do atributo [JsonIgnore] Condition
:The following example illustrates use of the [JsonIgnore] attribute's Condition
property:
#nullable enable
using System;
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 Main()
{
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}
Ignorar todas as propriedades somente leituraIgnore all read-only properties
Uma propriedade será somente leitura se ela contiver um getter público, mas não um setter público.A property is read-only if it contains a public getter but not a public setter. Para ignorar todas as propriedades somente leitura ao serializar, defina JsonSerializerOptions.IgnoreReadOnlyProperties como true
, conforme mostrado no exemplo a seguir:To ignore all read-only properties when serializing, set the JsonSerializerOptions.IgnoreReadOnlyProperties to true
, as shown in the following example:
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)
Aqui está um tipo de exemplo para serializar e a saída JSON:Here's an example type to serialize and JSON output:
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",
}
Essa opção se aplica somente à serialização.This option applies only to serialization. Durante a desserialização, as propriedades somente leitura são ignoradas por padrão.During deserialization, read-only properties are ignored by default.
Essa opção se aplica somente a propriedades.This option applies only to properties. Para ignorar campos somente leitura ao serializar campos, use a JsonSerializerOptions.IgnoreReadOnlyFields configuração global.To ignore read-only fields when serializing fields, use the JsonSerializerOptions.IgnoreReadOnlyFields global setting.
Ignorar todas as propriedades de valor nuloIgnore all null-value properties
Para ignorar todas as propriedades de valor nulo, defina a DefaultIgnoreCondition propriedade como WhenWritingNull , conforme mostrado no exemplo a seguir:To ignore all null-value properties, set the DefaultIgnoreCondition property to WhenWritingNull, as shown in the following example:
#nullable enable
using System;
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 Main()
{
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}
Para ignorar todas as propriedades de valor nulo ao serializar, defina a IgnoreNullValues propriedade como true
, conforme mostrado no exemplo a seguir:To ignore all null-value properties when serializing, set the IgnoreNullValues property to true
, as shown in the following example:
var options = new JsonSerializerOptions
{
IgnoreNullValues = true,
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(weatherForecast, options);
Dim options As JsonSerializerOptions = New JsonSerializerOptions With {
.IgnoreNullValues = True,
.WriteIndented = True
}
jsonString = JsonSerializer.Serialize(weatherForecast1, options)
Aqui está um objeto de exemplo para serializar e a saída JSON:Here's an example object to serialize and JSON output:
PropriedadeProperty | ValorValue |
---|---|
Date |
8/1/2019 12:00:00 AM -07:00 |
TemperatureCelsius |
25 |
Summary |
null |
{
"Date": "2019-08-01T00:00:00-07:00",
"TemperatureCelsius": 25
}
Ignorar todas as propriedades de valor padrãoIgnore all default-value properties
Para evitar a serialização de valores padrão em Propriedades de tipo de valor, defina a DefaultIgnoreCondition propriedade como WhenWritingDefault , conforme mostrado no exemplo a seguir:To prevent serialization of default values in value type properties, set the DefaultIgnoreCondition property to WhenWritingDefault, as shown in the following example:
#nullable enable
using System;
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 Main()
{
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"}
A WhenWritingDefault configuração também impede a serialização de tipo de referência de valor nulo e propriedades de tipo de valor anulável.The WhenWritingDefault setting also prevents serialization of null-value reference type and nullable value type properties.
Não há uma maneira interna de impedir a serialização de propriedades com padrões de tipo de valor no System.Text.Json
.NET Core 3,1.There is no built-in way to prevent serialization of properties with value type defaults in System.Text.Json
in .NET Core 3.1.
Veja tambémSee also
- System.Text.Json sobreSystem.Text.Json overview
- Como serializar e desserializar JSONHow to serialize and deserialize JSON
- Instanciar instâncias JsonSerializerOptionsInstantiate JsonSerializerOptions instances
- Habilitar a correspondência sem diferenciação de maiúsculas e minúsculasEnable case-insensitive matching
- Personalizar nomes e valores da propriedadeCustomize property names and values
- Permitir JSON inválidoAllow invalid JSON
- Manipular JSON de estouroHandle overflow JSON
- Preservar referênciasPreserve references
- Tipos imutáveis e acessadores não públicosImmutable types and non-public accessors
- Serialização polimórficaPolymorphic serialization
- Migrar do Newtonsoft.Json para o System.Text.JsonMigrate from Newtonsoft.Json to System.Text.Json
- Personalizar codificação de caracteresCustomize character encoding
- Escrever serializadores personalizados e desserializadoresWrite custom serializers and deserializers
- Gravar conversores personalizados para serialização JSONWrite custom converters for JSON serialization
- Suporte a DateTime e DateTimeOffsetDateTime and DateTimeOffset support
- System.Text.Json Referência de APISystem.Text.Json API reference
- System.Text.Json. Referência de API de serializaçãoSystem.Text.Json.Serialization API reference