소스 생성기를 사용하여 ASP.NET Core JSON API 속도 향상 | Khalid Abuhakmeh

이 게시물에서는 .NET 6에서 제공되는 최신 JSON 소스 생성기를 사용하여 JSON API 성능을 개선하고 응답 처리량을 늘리는 방법을 살펴봅니다.

.NET의 많은 소스 생성기와 마찬가지로 System.Text.Json 소스 생성기는 직렬화에 필요한 필수 요소로 기존 부분 클래스를 개선합니다. 이러한 요소는 다음과 같습니다:

  • 객체 그래프에서 직렬화 가능한 각 엔티티에 대한 JsonTypeInfo<T>
  • JsonSerializerContext의 기본 인스턴스.
  • 직렬화 시 JSON 형식을 지정하기 위한 JsonSerialiazerOptions
using System.Text.Json;
using System.Text.Json.Serialization;


var p = new Person("dimohy", Friend: new("spowner", Friend: new("fmsoul")));

var json = JsonSerializer.Serialize(p, PersonSerializationContext.Default.Person);
Console.WriteLine(json);


public record Person(
    string Name,
    bool IsCool = true,
    Person? Friend = default
);


[JsonSourceGenerationOptions(
    WriteIndented = true,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(Person))]
public partial class PersonSerializationContext : JsonSerializerContext
{
}

| 출력 결과

{
  "name": "dimohy",
  "isCool": true,
  "friend": {
    "name": "fmsoul",
    "isCool": true,
    "friend": {
      "name": "spowner",
      "isCool": true
    }
  }
}

4개의 좋아요