Taal

Eigenschappen negeren met System.Text.Json

Bij het serialiseren van C#-objecten naar JavaScript Object Notation (JSON), worden standaard alle openbare eigenschappen geserialiseerd. Als u niet wilt dat sommige van deze worden weergegeven in de resulterende JSON, hebt u verschillende opties. In dit artikel leert u hoe u eigenschappen kunt negeren op basis van verschillende criteria:

Afzonderlijke eigenschappen negeren

Gebruik het kenmerk [JsonIgnore] om afzonderlijke eigenschappen te negeren.

In het volgende voorbeeld ziet u een type dat u wilt serialiseren. Ook wordt de JSON-uitvoer weergegeven:

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,
}

U kunt voorwaardelijke uitsluiting opgeven door de eigenschap van het kenmerk Condition in te stellen. De JsonIgnoreCondition opsomming biedt de volgende opties:

  • Always - De eigenschap wordt altijd genegeerd. Als er geen Condition is opgegeven, wordt van deze optie uitgegaan.
  • Never - De eigenschap wordt altijd geserialiseerd en gedeserialiseerd, ongeacht de DefaultIgnoreCondition, IgnoreReadOnlyPropertiesen IgnoreReadOnlyFields globale instellingen.
  • WhenWritingDefault - De eigenschap wordt genegeerd bij serialisatie als het een verwijzingstype null, een type null-waarde nullof een waardetype defaultis.
  • WhenWritingNull - De eigenschap wordt genegeerd bij serialisatie als het een verwijzingstype nullof een null-waardetype nullis.

In het volgende voorbeeld ziet u het gebruik van de eigenschap van het kenmerk 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}

Eigenschappen negeren op basis van een voorwaarde op typeniveau

Vanaf .NET 11 past u [JsonIgnore(Condition = ...)] toe op een klasse, struct of interface om de standaard negeervoorwaarde voor de eigenschappen en velden in te stellen:

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public class Forecast
{
    public string? Summary { get; set; }
}
<JsonIgnore(Condition:=JsonIgnoreCondition.WhenWritingNull)>
Public Class Forecast
    Public Property Summary As String
End Class

De serializer past negeerinstellingen in deze volgorde toe, van hoogste naar laagste prioriteit:

Op typeniveau Always is dit ongeldig. Op reflectie gebaseerde serialisatie veroorzaakt een InvalidOperationException, en brongeneratie meldt SYSLIB1226. Omdat Always de standaardvoorwaarde is, geeft u Condition op wanneer u [JsonIgnore] op een type toepast.

Een op typeniveau gedefinieerde voorwaarde WhenWritingNull negeert niet-nullbare leden van waardetypen niet. De voorwaarde op typeniveau overschrijft nog steeds de globale DefaultIgnoreConditionvoorwaarde, zodat deze leden in de JSON blijven, zelfs wanneer de globale voorwaarde is WhenWritingDefault.

Alle alleen-lezeneigenschappen negeren

Een eigenschap heeft het kenmerk Alleen-lezen als deze een openbare getter bevat, maar geen openbare setter. Als u alle alleen-lezeneigenschappen wilt negeren bij het serialiseren, stelt u JsonSerializerOptions.IgnoreReadOnlyProperties in op true, zoals in het volgende voorbeeld wordt weergegeven:

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)

In het volgende voorbeeld ziet u een type dat u wilt serialiseren. Ook wordt de JSON-uitvoer weergegeven:

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",
}

Deze optie is alleen van toepassing op eigenschappen. Als u alleen-lezenvelden wilt negeren bij het serialiseren van velden, gebruikt u de JsonSerializerOptions.IgnoreReadOnlyFields globale instelling.

Opmerking

Alleen-lezen verzamelingstype-eigenschappen worden nog steeds geserialiseerd, zelfs als JsonSerializerOptions.IgnoreReadOnlyProperties is ingesteld op true.

Alle eigenschappen van null-waarde negeren

Als u alle eigenschappen met null-waarden wilt negeren, stelt u de DefaultIgnoreCondition eigenschap WhenWritingNullin op , zoals wordt weergegeven in het volgende voorbeeld:

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}

Alle eigenschappen van de standaardwaarde negeren

Als u serialisatie van standaardwaarden in eigenschappen van het waardetype wilt voorkomen, stelt u de DefaultIgnoreCondition eigenschap WhenWritingDefaultin op , zoals wordt weergegeven in het volgende voorbeeld:

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"}

De instelling WhenWritingDefault voorkomt ook de serialisering van eigenschappen van referentietypen met null-waarden en van nullable-waardetypen.

Zie ook