Anteckning
Åtkomst till den här sidan kräver auktorisering. Du kan prova att logga in eller ändra kataloger.
Åtkomst till den här sidan kräver auktorisering. Du kan prova att ändra kataloger.
När C#-objekt serialiseras till JavaScript Object Notation (JSON) serialiseras som standard alla offentliga egenskaper. Om du inte vill att några av dem ska visas i den resulterande JSON:en har du flera alternativ. I den här artikeln får du lära dig hur du ignorerar egenskaper baserat på olika kriterier:
- Enskilda egenskaper
- Alla skrivskyddade attribut
- Alla null-värdeegenskaper
- Alla standardvärdeegenskaper
Ignorera enskilda egenskaper
Om du vill ignorera enskilda egenskaper använder du attributet [JsonIgnore].
I följande exempel visas en typ som ska serialiseras. Den visar också JSON-utdata:
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,
}
Du kan ange villkorsstyrd exkludering genom att ange attributet [JsonIgnore] egenskap Condition . Uppräkningen JsonIgnoreCondition innehåller följande alternativ:
- 
              Always- Egenskapen ignoreras alltid. Om ingetConditionanges antas det här alternativet.
- 
              Never- Egenskapen serialiseras och deserialiseras alltid, oavsettDefaultIgnoreCondition,IgnoreReadOnlyPropertiesochIgnoreReadOnlyFieldsglobala inställningar.
- 
              WhenWritingDefault- Egenskapen ignoreras vid serialisering om det är en referenstypnull, en nullbar värdetypnulleller en värdetypdefault.
- 
              WhenWritingNull- Egenskapen ignoreras vid serialisering om det är en referenstypnulleller en nullbar värdetypnull.
I följande exempel visas hur attributet Condition används:
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}
Ignorera alla skrivskyddade egenskaper
En egenskap är skrivskyddad om den innehåller en offentlig getter men inte en offentlig setter. Om du vill ignorera alla skrivskyddade egenskaper vid serialisering anger du JsonSerializerOptions.IgnoreReadOnlyProperties till true, enligt följande exempel:
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)
I följande exempel visas en typ som ska serialiseras. Den visar också JSON-utdata:
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",
}
Det här alternativet gäller endast för egenskaper. Om du vill ignorera skrivskyddade fält vid serialisering av fält använder du den JsonSerializerOptions.IgnoreReadOnlyFields globala inställningen.
Anmärkning
Skrivskyddade egenskaper av samlingstyp serialiseras fortfarande även om JsonSerializerOptions.IgnoreReadOnlyProperties är inställt på true.
Ignorera alla null-värdeegenskaper
Om du vill ignorera alla null-värdeegenskaper anger du DefaultIgnoreCondition egenskapen till WhenWritingNull, enligt följande exempel:
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}
Ignorera alla standardvärdeegenskaper
Om du vill förhindra serialisering av standardvärden i värdetypsegenskaper anger du DefaultIgnoreCondition egenskapen till WhenWritingDefault, som du ser i följande exempel:
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"}
Inställningen WhenWritingDefault förhindrar även serialisering av null-värdereferenstyp och nullbara värdetypsegenskaper.