Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - JSON 역/직렬화 시 리플렉션 손실을 없애는 JsonSrcGen

Source Generator를 이용해,

C# - Source Generator 소개
; https://www.sysnet.pe.kr/2/0/12223

Reflection 단계를 없애고 JSON을 직렬화/역직렬화하는 nuget 패키지가 나왔습니다. ^^

Is the era of reflection-heavy C# libraries at an end?
; https://blog.marcgravell.com/2021/05/is-era-of-reflection-heavy-c-libraries.html

JsonSrcGen
; https://github.com/trampster/JsonSrcGen

따라서 단순히 JsonSrcGen 패키지만 참조 추가하고, 다음과 같이 적절하게 특성을 적용해 주면 JSON 직렬화/역직렬화를 고속으로 수행할 수 있습니다.

using System;
using JsonSrcGen;

namespace ConsoleApp2
{
    // Install-Package JsonSrcGen
    class Program
    {
        static void Main(string[] args)
        {
            var converter = new JsonConverter();

            ReadOnlySpan<char> json = converter.ToJson(new MyType() { MyProperty = "Some value" });
            Console.WriteLine(json.ToString());

            var myType = new MyType();
            converter.FromJson(myType, "{ \"my_name\" : \"Some value\" }");
            // 또는, converter.FromJson(myType, json);

            Console.WriteLine(myType);
        }
    }


    [Json]
    public class MyType
    {
        [JsonName("my_name")]
        public string MyProperty { get; set; }

        [JsonIgnore]
        public string IgnoredProperty { get; set; }

        public override string ToString()
        {
            return $"MyProperty = {MyProperty}";
        }
    }
}

/* 출력 결과
{"my_name":"Some value"}
MyProperty = Some value
*/

이때 Source Generator가 자동 생성하는 코드는 JsonConverter이고, 위와 같은 경우 MyType에 대해 다음과 같은 식의 소스 코드를 생성해 냅니다.

// %LOCALAPPDATA%\Temp\VSGeneratedDocuments\6aae0b5e-b25f-5c50-066b-6883b1eb7a7f\JsonConverter.cs

using System;
using System.Text;
using System.Collections.Generic;

namespace JsonSrcGen
{
#nullable enable
    public class JsonConverter
    {
        [ThreadStatic]
        JsonStringBuilder? Builder;
        public ReadOnlySpan<char> ToJson(ConsoleApp2.MyType value)
        {

            var builder = Builder;
            if(builder == null)
            {
                builder = new JsonStringBuilder();
                Builder = builder;
            }
            builder.Clear();
            ToJson(value, builder);
            return builder.AsSpan();
        }
        public void ToJson(ConsoleApp2.MyType value, JsonStringBuilder builder)
        {
            if(value.MyProperty == null)
            {
                builder.Append("{\"my_name\":null");
            }
            else
            {
                builder.Append("{\"my_name\":\"");
                builder.AppendEscaped(value.MyProperty);
                builder.Append("\"");
            }
            builder.Append("}");
        }
        public ReadOnlySpan<char> FromJson(ConsoleApp2.MyType value, ReadOnlySpan<char> json)
        {
            json = json.SkipWhitespaceTo('{');
            while(true)
            {
                json = json.SkipWhitespace();
                char value452 = json[0];
                if(value452 == '\"')
                {
                    json = json.Slice(1);
                }
                else if(value452 == '}')
                {
                    return json.Slice(1);
                }
                else
                {
                    throw new InvalidJsonException($"Unexpected character! expected '}}' or '\"' but got '{value452}'", json);
                }
                var propertyName = json.ReadTo('\"');
                json = json.Slice(propertyName.Length + 1);
                json = json.SkipWhitespaceTo(':');
                switch(propertyName.Length % 1)
                {
                    case 0:
                        if(!propertyName.EqualsString("my_name"))
                        {
                            json = json.SkipProperty();
                            break;
                        }
                        json = json.Read(out string? property453Value);
                        value.MyProperty = property453Value;
                        break;
                }
                json = json.SkipWhitespace();
                if(json[0] == ',')
                {
                    json = json.Slice(1);
                }
            }
        }
    }
}
#nullable restore

재미있군요. ^^ 현재 .NET Core 2.1 이상의 프로젝트에서 사용할 수 있습니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




(아래의 버그는 1.1 버전에서 해결될 거라고 합니다. ^^ 대응이 무척 빠르군요.)

참고로, JsonSrcGen 대상이 되는 타입을 namespace 없이 정의하면,

using System;
using JsonSrcGen;

/*
namespace ConsoleApp2
{
*/
    [Json]
    public class MyType
    {
        [JsonName("my_name")]
        public string MyProperty { get; set; }

        [JsonIgnore]
        public string IgnoredProperty { get; set; }
    }
// }

이런 식의 무수한 컴파일 오류 메시지를 보게 될 것입니다. ^^;

Error CS0501 '<invalid-global-code>.<invalid-global-code>(value, builder)' must declare a body because it is not marked abstract, extern, or partial

Error CS0501 'JsonConverter.ToJson(global)' must declare a body because it is not marked abstract, extern, or partial

Error CS0116 A namespace cannot directly contain members such as fields or methods

Error CS1520 Method must have a return type

아직 1.0.3의 초기 버전이라 현업에 적용하실 때는 적절한 사전 검증 작업이 필요할 듯합니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/25/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-07-30 09시43분
정성태
2023-01-20 08시30분
riok/mapperly
; https://github.com/riok/mapperly

A .NET source generator for generating object mappings. No runtime reflection. Inspired by MapStruct.
정성태

1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13474정성태12/6/20232133개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232325닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232155C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232183Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232483닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232192닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232175닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232170오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232376닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232109개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232228닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232144오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232209오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232258닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232224닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232207닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232212닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232163VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232459닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232339닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232681닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232217오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232296닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232431닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232253닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232351개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...