이 문서에서는 System.Text.Json 네임스페이스를 사용하여 JSON(JavaScript Object Notation)으로부터 역직렬화하는 방법을 보여줍니다.
Newtonsoft.Json에서 기존 코드를 이식하는 경우 System.Text.Json으로 마이그레이션 방법을 참조하세요.
JSON을 역직렬화하는 일반적인 방법은 하나 이상의 JSON 속성을 나타내는 속성 및 필드가 있는 .NET 클래스를 갖거나 만드는 것입니다. 그런 다음 문자열 또는 파일에서 역직렬화하려면 JsonSerializer.Deserialize 메서드를 호출합니다. 제네릭 오버로드의 경우 제네릭 형식 매개 변수는 .NET 클래스입니다. 제네릭이 아닌 오버로드의 경우 클래스의 형식을 메서드 매개 변수로 전달합니다. 동기적 또는 비동기적으로 역직렬화할 수 있습니다.
팁
AI 지원을 사용하여 JSON 문자열을 역직렬화할 수 있습니다.
클래스에 표시되지 않는 JSON 속성은 기본적으로 무시됩니다. 또한 형식의 필수 속성이 JSON 페이로드에 없는 경우 역직렬화가 실패합니다.
예제
다음 예제에서는 컬렉션 및 중첩된 개체를 포함하는 JSON 문자열을 역직렬화하는 방법을 보여 줍니다.
using System.Text.Json;
namespace DeserializeExtra
{
public class WeatherForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
public string? SummaryField;
public IList<DateTimeOffset>? DatesAvailable { get; set; }
public Dictionary<string, HighLowTemps>? TemperatureRanges { get; set; }
public string[]? SummaryWords { get; set; }
}
public class HighLowTemps
{
public int High { get; set; }
public int Low { get; set; }
}
public class Program
{
public static void Main()
{
string jsonString =
"""
{
"Date": "2019-08-01T00:00:00-07:00",
"TemperatureCelsius": 25,
"Summary": "Hot",
"DatesAvailable": [
"2019-08-01T00:00:00-07:00",
"2019-08-02T00:00:00-07:00"
],
"TemperatureRanges": {
"Cold": {
"High": 20,
"Low": -10
},
"Hot": {
"High": 60,
"Low": 20
}
},
"SummaryWords": [
"Cool",
"Windy",
"Humid"
]
}
""";
WeatherForecast? weatherForecast =
JsonSerializer.Deserialize<WeatherForecast>(jsonString);
Console.WriteLine($"Date: {weatherForecast?.Date}");
Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}");
Console.WriteLine($"Summary: {weatherForecast?.Summary}");
if (weatherForecast?.DatesAvailable != null)
{
foreach (DateTimeOffset dateTimeOffset in weatherForecast.DatesAvailable)
{
Console.WriteLine($"DateAvailable: {dateTimeOffset}");
}
}
if (weatherForecast?.TemperatureRanges != null)
{
foreach (KeyValuePair<string, HighLowTemps> temperatureRange in weatherForecast.TemperatureRanges)
{
Console.WriteLine($"TemperatureRange: {temperatureRange.Key} is {temperatureRange.Value.Low} to {temperatureRange.Value.High}");
}
}
if (weatherForecast?.SummaryWords != null)
{
foreach (string summaryWord in weatherForecast.SummaryWords)
{
Console.WriteLine($"SummaryWord: {summaryWord}");
}
}
}
}
}
/* Output:
*
* Date: 8/1/2019 12:00:00 AM -07:00
* TemperatureCelsius: 25
* Summary: Hot
* DateAvailable: 8/1/2019 12:00:00 AM -07:00
* DateAvailable: 8/2/2019 12:00:00 AM -07:00
* TemperatureRange: Cold is -10 to 20
* TemperatureRange: Hot is 20 to 60
* SummaryWord: Cool
* SummaryWord: Windy
* SummaryWord: Humid
* */
Imports System.Text.Json
Namespace DeserializeExtra
Public Class WeatherForecast
Public Property [Date] As DateTimeOffset
Public Property TemperatureCelsius As Integer
Public Property Summary As String
Public SummaryField As String
Public Property DatesAvailable As IList(Of DateTimeOffset)
Public Property TemperatureRanges As Dictionary(Of String, HighLowTemps)
Public Property SummaryWords As String()
End Class
Public Class HighLowTemps
Public Property High As Integer
Public Property Low As Integer
End Class
Public NotInheritable Class Program
Public Shared Sub Run()
Dim jsonString As String =
"{
""Date"": ""2019-08-01T00:00:00-07:00"",
""TemperatureCelsius"": 25,
""Summary"": ""Hot"",
""DatesAvailable"": [
""2019-08-01T00:00:00-07:00"",
""2019-08-02T00:00:00-07:00""
],
""TemperatureRanges"": {
""Cold"": {
""High"": 20,
""Low"": -10
},
""Hot"": {
""High"": 60,
""Low"": 20
}
},
""SummaryWords"": [
""Cool"",
""Windy"",
""Humid""
]
}"
Dim weatherForecast As WeatherForecast =
JsonSerializer.Deserialize(Of WeatherForecast)(jsonString)
Console.WriteLine($"Date: {weatherForecast?.Date}")
Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}")
Console.WriteLine($"Summary: {weatherForecast?.Summary}")
If weatherForecast?.DatesAvailable IsNot Nothing Then
For Each dateTimeOffset As DateTimeOffset In weatherForecast.DatesAvailable
Console.WriteLine($"DateAvailable: {dateTimeOffset}")
Next
End If
If weatherForecast?.TemperatureRanges IsNot Nothing Then
For Each temperatureRange As KeyValuePair(Of String, HighLowTemps) In weatherForecast.TemperatureRanges
Console.WriteLine($"TemperatureRange: {temperatureRange.Key} is {temperatureRange.Value.Low} to {temperatureRange.Value.High}")
Next
End If
If weatherForecast?.SummaryWords IsNot Nothing Then
For Each summaryWord As String In weatherForecast.SummaryWords
Console.WriteLine($"SummaryWord: {summaryWord}")
Next
End If
End Sub
End Class
End Namespace
' Output:
'
'Date: 8/1/2019 12:00:00 AM -07:00
'TemperatureCelsius: 25
'Summary: Hot
'DateAvailable: 8/1/2019 12:00:00 AM -07:00
'DateAvailable: 8/2/2019 12:00:00 AM -07:00
'TemperatureRange: Cold is -10 to 20
'TemperatureRange: Hot is 20 to 60
'SummaryWord: Cool
'SummaryWord: Windy
'SummaryWord: Humid
동기 코드를 사용하여 파일에서 역직렬화하려면 다음 예제와 같이 파일을 문자열로 읽습니다.
using System.Text.Json;
namespace DeserializeFromFile
{
public class WeatherForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
}
public class Program
{
public static void Main()
{
string fileName = "WeatherForecast.json";
string jsonString = File.ReadAllText(fileName);
WeatherForecast weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString)!;
Console.WriteLine($"Date: {weatherForecast.Date}");
Console.WriteLine($"TemperatureCelsius: {weatherForecast.TemperatureCelsius}");
Console.WriteLine($"Summary: {weatherForecast.Summary}");
}
}
}
// output:
//Date: 8/1/2019 12:00:00 AM -07:00
//TemperatureCelsius: 25
//Summary: Hot
jsonString = File.ReadAllText(fileName)
weatherForecast1 = JsonSerializer.Deserialize(Of WeatherForecast)(jsonString)
비동기 코드를 사용하여 파일에서 역직렬화하려면 DeserializeAsync 메서드를 호출합니다.
using System.Text.Json;
namespace DeserializeFromFileAsync
{
public class WeatherForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
}
public class Program
{
public static async Task Main()
{
string fileName = "WeatherForecast.json";
using FileStream openStream = File.OpenRead(fileName);
WeatherForecast? weatherForecast =
await JsonSerializer.DeserializeAsync<WeatherForecast>(openStream);
Console.WriteLine($"Date: {weatherForecast?.Date}");
Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}");
Console.WriteLine($"Summary: {weatherForecast?.Summary}");
}
}
}
// output:
//Date: 8/1/2019 12:00:00 AM -07:00
//TemperatureCelsius: 25
//Summary: Hot
Dim openStream As FileStream = File.OpenRead(fileName)
weatherForecast1 = Await JsonSerializer.DeserializeAsync(Of WeatherForecast)(openStream)
역직렬화 동작
JSON을 역직렬화할 때 다음 동작이 적용됩니다.
- 기본적으로, 속성 이름 일치 시에 대/소문자를 구분합니다. 대/소문자를 구분 하지 않도록 지정할 수 있습니다.
- public이 아닌 생성자는 직렬 변환기에서 무시됩니다.
- 변경 불가능한 개체 또는 퍼블릭
set접근자가 없는 속성에 대한 Deserialization이 지원되지만 기본적으로 활성화되지는 않습니다. 변경 불가능한 형식 및 레코드를 참조하세요. - 기본적으로 열거형은 숫자로 지원됩니다. 문자열 열거형 필드 역직렬화를 수행할 수 있습니다.
- 기본적으로 필드는 무시됩니다. 필드를 포함할 수 있습니다.
- 기본적으로 JSON의 주석이나 후행 쉼표는 예외를 발생시킵니다. 주석과 후행 쉼표를 허용할 수 있습니다.
- 기본 최댓값은 64입니다.
ASP.NET Core 앱에서 System.Text.Json을 간접적으로 사용하는 경우 몇 가지 기본 동작이 다릅니다. 자세한 내용은 JsonSerializerOptions 웹 기본값을 참조하세요.
기본 변환기에서 지원하지 않는 기능을 제공하는 사용자 지정 변환기를 구현할 수 있습니다.
.NET 클래스 없이 역직렬화
역직렬화하려는 JSON이 있고 역직렬화 대상 클래스가 없는 경우 필요한 클래스를 수동으로 만드는 것 외에 다른 옵션이 있습니다.
Utf8JsonReader를 직접 사용합니다.
JSON DOM(문서 개체 모델)으로 역직렬화하고 DOM에서 필요한 항목을 추출합니다.
DOM을 사용하면 JSON 페이로드의 하위 섹션으로 이동하고 단일 값, 사용자 지정 형식 또는 배열을 역직렬화할 수 있습니다. JsonNode DOM에 대한 자세한 내용은 JSON 페이로드의 하위 섹션 역직렬화를 참조하세요. JsonDocument DOM에 대한 자세한 내용은 JsonDocument 및 JsonElement에서 하위 요소를 검색하는 방법을 참조하세요.
Visual Studio 2022 이상을 사용하여 필요한 클래스를 자동으로 생성합니다.
- 역직렬화해야 하는 JSON을 복사합니다.
- 클래스 파일을 만들고 템플릿 코드를 삭제합니다.
- 편집>특수 붙여넣기>JSON을 클래스로 붙여넣기를 선택합니다.
결과는 역직렬화 대상에 사용할 수 있는 클래스입니다.
UTF-8에서 역직렬화
UTF-8에서 역직렬화하려면 다음 예제와 같이 JsonSerializer.Deserialize 또는 ReadOnlySpan<byte>을 사용하는 Utf8JsonReader 오버로드를 호출합니다. 이 예제에서는 JSON이 jsonUtf8Bytes라는 바이트 배열에 있다고 가정합니다.
var readOnlySpan = new ReadOnlySpan<byte>(jsonUtf8Bytes);
WeatherForecast deserializedWeatherForecast =
JsonSerializer.Deserialize<WeatherForecast>(readOnlySpan)!;
Dim jsonString = Encoding.UTF8.GetString(jsonUtf8Bytes)
weatherForecast1 = JsonSerializer.Deserialize(Of WeatherForecast)(jsonString)
var utf8Reader = new Utf8JsonReader(jsonUtf8Bytes);
WeatherForecast deserializedWeatherForecast =
JsonSerializer.Deserialize<WeatherForecast>(ref utf8Reader)!;
' This code example doesn't apply to Visual Basic. For more information, go to the following URL:
' https://learn.microsoft.com/dotnet/standard/serialization/system-text-json-how-to#visual-basic-support
AI를 사용하여 JSON 역직렬화
GitHub Copilot와 같은 AI 도구를 사용하여 JSON에서 역직렬화하는 데 사용하는 System.Text.Json 코드를 생성할 수 있습니다. 예를 들어 대상 클래스가 JSON 입력에서 누락된 속성을 정의할 때 역직렬화를 보여 주도록 프롬프트를 사용자 지정할 수 있습니다.
다음 텍스트는 Copilot 채팅의 프롬프트 예를 보여줍니다.
Generate C# code to use System.Text.Json to deserialize a JSON string {"FirstName":"John","LastName":"Doe"} to an equivalent .NET object, where the class defines an Age property.
Show what happens when the JSON is missing a property defined in the class.
Provide example output.
코필로트의 제안을 적용하기 전에 검토합니다.
GitHub Copilot에 대한 자세한 내용은 GitHub의 FAQ를 참조하세요.
참고하십시오
- 인터페이스로 역직렬화하는 방법
- Visual Studio의 GitHub Copilot
- Visual Studio Code의 GitHub Copilot
.NET