C# 개체를 JSON(JavaScript Object Notation)으로 serialize하는 경우 기본적으로 모든 공용 속성이 serialize됩니다. 그 중 일부를 결과 JSON에 표시하지 않으려면 몇 가지 옵션이 있습니다. 이 문서에서는 다양한 조건에 따라 속성을 무시하는 방법을 알아봅니다.
개별 속성 무시
개별 속성을 무시하려면 [JsonIgnore] 특성을 사용합니다.
다음 예제에서는 serialize할 형식을 보여줍니다. 또한 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
- 속성이 참조 형식일 때, nullable 값 형식null
일 때, 또는 값 형식null
일 때 serialization에서 무시됩니다default
. -
WhenWritingNull
- 속성이 참조 형식이거나 nullable 값 형식null
인 경우 serialization에서 무시됩니다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가 없는 경우 속성은 읽기 전용입니다. serialize할 때 모든 읽기 전용 속성을 무시하려면 다음 예제와 같이 다음으로 설정합니다 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)
다음 예제에서는 serialize할 형식을 보여줍니다. 또한 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-value 속성 무시
모든 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}
모든 기본값 속성 무시
값 형식 속성에서 기본값이 serialization되지 않도록 하려면 다음 예제와 같이 속성을 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-value 참조 형식 및 nullable 값 형식 속성의 serialization을 방지합니다.
참고하십시오
.NET