필수 속성
.NET 7부터 deserialization이 성공하려면 JSON 페이로드에 있어야 함을 나타내기 위해 특정 속성을 표시할 수 있습니다. 이러한 필수 속성 중 하나 이상이 없는 경우 JsonSerializer.Deserialize 메서드는 JsonException을 throw합니다.
JSON deserialization에 필요한 속성 또는 필드를 표시하는 방법에는 다음 세 가지가 있습니다.
- 필수 한정자 추가(C# 11의 새로운 기능)
- JsonRequiredAttribute를 사용하여 주석 처리(.NET 7의 새로운 기능)
- 계약 모델의 JsonPropertyInfo.IsRequired 속성 수정(.NET 7의 새로운 기능)
직렬 변환기의 관점에서 볼 때 이러한 두 경계는 동일하며 둘 다 동일한 메타데이터 조각(JsonPropertyInfo.IsRequired)에 매핑됩니다. 대부분의 경우 기본 제공 C# 키워드만 사용합니다. 그러나 다음 경우에는 JsonRequiredAttribute를 대신 사용해야 합니다.
- C# 이외의 프로그래밍 언어 또는 C#의 하위 수준 버전을 사용하는 경우
- JSON deserialization에만 적용하려는 경우
- 원본 생성 모드에서
System.Text.Json
serialization을 사용하는 경우 여기서는 소스 생성이 컴파일 시간에 발생하므로required
한정자를 사용하는 경우 코드가 컴파일되지 않습니다.
다음 코드 조각은 required
키워드로 수정된 속성의 예를 보여 줍니다. deserialization이 성공하려면 이 속성이 JSON 페이로드에 있어야 합니다.
using System.Text.Json;
// The following line throws a JsonException at run time.
Console.WriteLine(JsonSerializer.Deserialize<Person>("""{"Age": 42}"""));
public class Person
{
public required string Name { get; set; }
public int Age { get; set; }
}
또는 JsonRequiredAttribute를 사용할 수 있습니다.
using System.Text.Json;
// The following line throws a JsonException at run time.
Console.WriteLine(JsonSerializer.Deserialize<Person>("""{"Age": 42}"""));
public class Person
{
[JsonRequired]
public string Name { get; set; }
public int Age { get; set; }
}
또한 JsonPropertyInfo.IsRequired 속성을 사용하여 계약 모델을 통해 속성이 필요한지 여부를 제어할 수도 있습니다.
var options = new JsonSerializerOptions
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers =
{
static typeInfo =>
{
if (typeInfo.Kind != JsonTypeInfoKind.Object)
return;
foreach (JsonPropertyInfo propertyInfo in typeInfo.Properties)
{
// Strip IsRequired constraint from every property.
propertyInfo.IsRequired = false;
}
}
}
}
};
// Deserialization now succeeds even though the Name property isn't in the JSON payload.
JsonSerializer.Deserialize<Person>("""{"Age": 42}""", options);
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기