System.Text.Json의 지원되는 컬렉션 형식

이 문서에서는 serialization 및 deserialization에 지원되는 컬렉션에 대한 개요를 제공합니다. System.Text.Json.JsonSerializer는 다음과 같은 경우 serialization에 대한 컬렉션 형식을 지원합니다.

serializer는 메서드를 GetEnumerator() 호출하고 요소를 씁니다.

Deserialization은 좀 더 복잡하며 일부 컬렉션 형식에서는 지원되지 않습니다.

다음 섹션은 네임스페이스별로 구성되며 serialization 및 deserialization에 지원되는 형식을 보여 줍니다.

System.Array 네임스페이스

형식 Serialization Deserialization
1차원 배열 ✔️ ✔️
다차원 배열
가변 배열 ✔️ ✔️

System.Collections 네임스페이스

형식 Serialization Deserialization
ArrayList ✔️ ✔️
BitArray ✔️
DictionaryEntry ✔️ ✔️
Hashtable ✔️ ✔️
ICollection ✔️ ✔️
IDictionary ✔️ ✔️
IEnumerable ✔️ ✔️
IList ✔️ ✔️
Queue ✔️ ✔️
SortedList ✔️ ✔️
Stack * ✔️ ✔️

* 유형에 대한 지원 왕복을 Stack 참조하세요.

System.Collections.Generic 네임스페이스

형식 Serialization Deserialization
Dictionary<TKey,TValue> * ✔️ ✔️
HashSet<T> ✔️ ✔️
IAsyncEnumerable<T> ✔️ ✔️
ICollection<T> ✔️ ✔️
IDictionary<TKey,TValue> * ✔️ ✔️
IEnumerable<T> ✔️ ✔️
IList<T> ✔️ ✔️
IReadOnlyCollection<T> ✔️ ✔️
IReadOnlyDictionary<TKey,TValue> * ✔️ ✔️
IReadOnlyList<T> ✔️ ✔️
ISet<T> ✔️ ✔️
KeyValuePair<TKey,TValue> ✔️ ✔️
LinkedList<T> ✔️ ✔️
LinkedListNode<T> ✔️
List<T> ✔️ ✔️
Queue<T> ✔️ ✔️
SortedDictionary<TKey,TValue> * ✔️ ✔️
SortedList<TKey,TValue> * ✔️ ✔️
SortedSet<T> ✔️ ✔️
Stack<T> ✔️ ✔️

* 지원되는 키 형식을 참조하세요.

† 다음 섹션을 IAsyncEnumerable<T>참조하세요.

• 유형에 대한 지원 왕복을 Stack 참조하세요.

IAsyncEnumerable<T>

다음 예제에서는 비동기 데이터 원본의 표현으로 스트림을 사용합니다. 원본은 로컬 컴퓨터의 파일이거나 데이터베이스 쿼리 또는 웹 서비스 API 호출의 결과일 수 있습니다.

serialization 스트리밍

System.Text.Json은 다음 예제와 같이 IAsyncEnumerable<T> 값을 jSON 배열로 직렬화할 수 있습니다.

using System.Text.Json;

namespace IAsyncEnumerableSerialize;

public class Program
{
    public static async Task Main()
    {
        using Stream stream = Console.OpenStandardOutput();
        var data = new { Data = PrintNumbers(3) };
        await JsonSerializer.SerializeAsync(stream, data);
    }

    static async IAsyncEnumerable<int> PrintNumbers(int n)
    {
        for (int i = 0; i < n; i++)
        {
            await Task.Delay(1000);
            yield return i;
        }
    }
}
// output:
//  {"Data":[0,1,2]}

IAsyncEnumerable<T> 값은 JsonSerializer.SerializeAsync와 같은 비동기 serialization 메서드에서만 지원됩니다.

deserialization 스트리밍

DeserializeAsyncEnumerable 메서드는 다음 예제와 같이 deserialization 스트리밍을 지원합니다.

using System.Text;
using System.Text.Json;

namespace IAsyncEnumerableDeserialize;

public class Program
{
    public static async Task Main()
    {
        using var stream = new MemoryStream(Encoding.UTF8.GetBytes("[0,1,2,3,4]"));
        await foreach (int item in JsonSerializer.DeserializeAsyncEnumerable<int>(stream))
        {
            Console.WriteLine(item);
        }
    }
}
// output:
//0
//1
//2
//3
//4

DeserializeAsyncEnumerable 메서드는 루트 수준 JSON 배열에서 읽기만 지원합니다.

DeserializeAsync 메서드는 IAsyncEnumerable<T>을 지원하지만 해당 서명은 스트리밍을 허용하지 않습니다. 다음 예제와 같이 최종 결과를 단일 값으로 반환합니다.

using System.Text;
using System.Text.Json;

namespace IAsyncEnumerableDeserializeNonStreaming;

public class MyPoco
{
    public IAsyncEnumerable<int>? Data { get; set; }
}

public class Program
{
    public static async Task Main()
    {
        using var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"{""Data"":[0,1,2,3,4]}"));
        MyPoco? result = await JsonSerializer.DeserializeAsync<MyPoco>(stream)!;
        await foreach (int item in result!.Data!)
        {
            Console.WriteLine(item);
        }
    }
}
// output:
//0
//1
//2
//3
//4

이 예제에서 역직렬 변환기는 역직렬화된 개체를 반환하기 전에 메모리의 모든 IAsyncEnumerable<T> 내용을 버퍼링합니다. 역직렬 변환기는 결과를 반환하기 전에 전체 JSON 페이로드를 읽어야 하기 때문에 이 동작이 필요합니다.

System.Collections.Immutable 네임스페이스

형식 Serialization Deserialization
IImmutableDictionary<TKey,TValue> ✔️ ✔️
IImmutableList<T> ✔️ ✔️
IImmutableQueue<T> ✔️ ✔️
IImmutableSet<T> ✔️ ✔️
IImmutableStack<T> * ✔️ ✔️
ImmutableArray<T> ✔️ ✔️
ImmutableDictionary<TKey,TValue> ✔️ ✔️
ImmutableHashSet<T> ✔️ ✔️
ImmutableQueue<T> ✔️ ✔️
ImmutableSortedDictionary<TKey,TValue> ✔️ ✔️
ImmutableSortedSet<T> ✔️ ✔️
ImmutableStack<T> * ✔️ ✔️

* 유형에 대한 지원 왕복을 Stack 참조하세요.

† 지원되는 키 형식을 참조 하세요.

System.Collections.Specialized 네임스페이스

형식 Serialization Deserialization
BitVector32 ✔️ ❌*
HybridDictionary ✔️ ✔️
IOrderedDictionary ✔️
ListDictionary ✔️ ✔️
NameValueCollection ✔️
StringCollection ✔️
StringDictionary ✔️

* BitVector32가 역직렬화되면 Data 속성은 public setter가 없으므로 건너뜁니다. 예외가 throw되지 않습니다.

System.Collections.Concurrent 네임스페이스

형식 Serialization Deserialization
BlockingCollection<T> ✔️
ConcurrentBag<T> ✔️
ConcurrentDictionary<TKey,TValue> ✔️ ✔️
ConcurrentQueue<T> ✔️ ✔️
ConcurrentStack<T> * ✔️ ✔️

* 유형에 대한 지원 왕복을 Stack 참조하세요.

† 지원되는 키 형식을 참조 하세요.

System.Collections.ObjectModel 네임스페이스

형식 Serialization Deserialization
Collection<T> ✔️ ✔️
KeyedCollection<string, TValue> * ✔️
ObservableCollection<T> ✔️ ✔️
ReadOnlyCollection<T> ✔️
ReadOnlyDictionary<TKey,TValue> ✔️
ReadOnlyObservableCollection<T> ✔️

* string 이외 키는 지원되지 않습니다.

사용자 지정 컬렉션

이전 네임스페이스 중 하나에 없는 컬렉션 형식은 사용자 지정 컬렉션으로 간주됩니다. 이러한 형식에는 사용자 정의 형식 및 ASP.NET Core에서 정의한 형식이 포함됩니다. 예를 들어 Microsoft.Extensions.Primitives는 이 그룹에 있습니다.

요소 형식이 지원되는 한, 모든 사용자 지정 컬렉션(IEnumerable에서 파생되는 모든 컬렉션)에서 serialization이 지원됩니다.

deserialization가 지원되는 사용자 지정 컬렉션

사용자 지정 컬렉션은 다음과 같은 경우 deserialization이 지원됩니다.

알려진 문제가 있는 사용자 지정 컬렉션

다음 사용자 지정 컬렉션에는 알려진 문제가 있습니다.

알려진 문제에 대한 자세한 내용은 System.Text.Json의 미해결 문제를 참조하세요.

지원되는 키 유형

DictionarySortedList 형식의 키에 대해 지원되는 형식은 다음과 같습니다.

  • Boolean
  • Byte
  • DateTime
  • DateTimeOffset
  • Decimal
  • Double
  • Enum
  • Guid
  • Int16
  • Int32
  • Int64
  • Object(serialization에서만, 런타임 형식이 이 목록에서 지원되는 형식 중 하나인 경우)
  • SByte
  • Single
  • String
  • UInt16
  • UInt32
  • UInt64

System.Data 네임스페이스

System.Data 네임스페이스에는 DataSet, DataTable 및 관련 형식에 대한 기본 제공 변환기가 없습니다. 보안 지침에 설명된 대로 신뢰할 수 없는 입력에서 이러한 형식을 역직렬화하는 것은 안전하지 않습니다. 그러나 이러한 형식을 지원하는 사용자 지정 변환기를 작성할 수 있습니다. DataTable을 직렬화 및 역직렬화하는 샘플 사용자 지정 변환기 코드는 RoundtripDataTable.cs를 참조하세요.

참고 항목