Jak ignorować właściwości za pomocą polecenia System.Text.Json

W przypadku serializacji obiektów języka C# do notacji obiektów JavaScript (JSON) domyślnie wszystkie właściwości publiczne są serializowane. Jeśli nie chcesz, aby niektóre z nich były wyświetlane w wynikowym formacie JSON, masz kilka opcji. Z tego artykułu dowiesz się, jak ignorować właściwości na podstawie różnych kryteriów:

Ignoruj poszczególne właściwości

Aby zignorować poszczególne właściwości, użyj atrybutu [JsonIgnore].

W poniższym przykładzie pokazano typ do serializacji. Wyświetla również dane wyjściowe 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,
}

Wykluczenie warunkowe można określić, ustawiając właściwość atrybutu Condition [JsonIgnore]. Wyliczenie JsonIgnoreCondition zawiera następujące opcje:

  • Always - Właściwość jest zawsze ignorowana. Jeśli nie Condition zostanie określona, przyjmuje się tę opcję.
  • Never - Właściwość jest zawsze serializowana i deserializowana, niezależnie od DefaultIgnoreConditionustawień globalnych , IgnoreReadOnlyPropertiesi IgnoreReadOnlyFields .
  • WhenWritingDefault - Właściwość jest ignorowana w serializacji, jeśli jest to typ nullodwołania , typ nullwartości dopuszczalnej wartości null lub typ defaultwartości .
  • WhenWritingNull - Właściwość jest ignorowana w serializacji, jeśli jest to typ nullodwołania , lub typ nullwartości dopuszczalnej wartości null .

Poniższy przykład ilustruje użycie właściwości atrybutu Condition [JsonIgnore]:

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}

Ignoruj wszystkie właściwości tylko do odczytu

Właściwość jest tylko do odczytu, jeśli zawiera publiczny moduł pobierający, ale nie publiczny. Aby zignorować wszystkie właściwości tylko do odczytu podczas serializacji, ustaw wartość JsonSerializerOptions.IgnoreReadOnlyPropertiestruena , jak pokazano w poniższym przykładzie:

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)

W poniższym przykładzie pokazano typ do serializacji. Wyświetla również dane wyjściowe 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",
}

Ta opcja ma zastosowanie tylko do właściwości. Aby zignorować pola tylko do odczytu podczas serializacji pól, użyj ustawienia globalnego JsonSerializerOptions.IgnoreReadOnlyFields .

Uwaga

Właściwości typu kolekcji tylko do odczytu są nadal serializowane, nawet jeśli JsonSerializerOptions.IgnoreReadOnlyProperties ustawiono wartość true.

Ignoruj wszystkie właściwości wartości null

Aby zignorować wszystkie właściwości null,ustaw DefaultIgnoreCondition właściwość na WhenWritingNull, jak pokazano w poniższym przykładzie:

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}

Ignoruj wszystkie właściwości wartości domyślnej

Aby zapobiec serializacji wartości domyślnych we właściwościach typu wartości, ustaw DefaultIgnoreCondition właściwość na WhenWritingDefault, jak pokazano w poniższym przykładzie:

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

Ustawienie WhenWritingDefault zapobiega również serializacji typu odwołania o wartości null i właściwościach typu wartości null.

Zobacz też