Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 9개 있습니다.)
.NET Framework: 351. JavaScriptSerializer, DataContractJsonSerializer, Json.NET
; https://www.sysnet.pe.kr/2/0/1391

.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법
; https://www.sysnet.pe.kr/2/0/11224

.NET Framework: 756. JSON의 escape sequence 문자 처리 방식
; https://www.sysnet.pe.kr/2/0/11532

사물인터넷: 54. 아두이노 환경에서의 JSON 파서(ArduinoJson) 사용법
; https://www.sysnet.pe.kr/2/0/11766

.NET Framework: 1073. C# - JSON 역/직렬화 시 리플렉션 손실을 없애는 JsonSrcGen
; https://www.sysnet.pe.kr/2/0/12688

.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json
; https://www.sysnet.pe.kr/2/0/13214

.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
; https://www.sysnet.pe.kr/2/0/13342

닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석
; https://www.sysnet.pe.kr/2/0/13623

닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리
; https://www.sysnet.pe.kr/2/0/13644




Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법

제목으로 표현하는 것이 매우 애매한데요. 직접 코드로 살펴보겠습니다.

예를 들어, 테이블 정보를 반환하는 json 응답이 다음과 같은 경우,

{
    "db_tables":
    {
        "name":"member_info"
    }
}

C#에서 class를 이런 식으로 구성하여,

public class DBTable
{
    public string name;
}

public class MyItem
{
    public DBTable db_tables;
}

역 직렬화하는 것이 가능합니다.

// txt == {"db_tables":{"name":"member_info"}}
MyItem item = Newtonsoft.Json.JsonConvert.DeserializeObject<MyItem>(txt);

그런데, 때로는 Web API 개발자가 다음과 같이 "테이블 명"을 속성 이름으로 사용하는 경우가 있습니다.

{
    "db_tables":
    {
        "member_info":"2017-06-13"
    }
}

테이블 이름은 바뀔 수 있는 값이기 때문에 이 필드에 맞춰 C# 클래스를 정의해 줄 수는 없으므로 기존 방법으로는 역 직렬화가 매우 불편하게 됩니다. 바로 이런 상황을 해결하는 용도로 JsonSerializerSettings 클래스가 제공됩니다.

Overwrite Json property name in c#
; https://stackoverflow.com/questions/26882986/overwrite-json-property-name-in-c-sharp

이 글의 예에서는 "member_info" 테이블 이름이 곧 속성 이름으로 사용된 것이기 때문에 이를 실행 중에 바꿀 수 있도록 다음과 같이 ContractResolver를 작성해 JsonSerializerSettings에 넘겨 주면 됩니다.

static void Main(string[] args)
{
    JsonSerializerSettings settings = new JsonSerializerSettings();
    settings.ContractResolver = new CustomNamesContractResolver();

    string txt = "{\"db_tables\":{\"member_info\":\"5\"}}";

    MyItem copy = Newtonsoft.Json.JsonConvert.DeserializeObject<MyItem>(txt, settings);
}

class CustomNamesContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(System.Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);

        foreach (JsonProperty prop in list)
        {
            if (prop.UnderlyingName == "name")
            {
                prop.PropertyName = "member_info";
            }
        }

        return list;
    }
}

대충 어떤 용도인지 아시겠죠? ^^

위의 예에서 약간 보완할 항목이라면, C# 클래스(DBTable)의 필드 이름을 "name"으로 주었지만 클래스가 중첩된 경우 필드 이름이 중복될 가능성이 있으므로 "___dbtable_name___"과 같은 식으로 대체하는 것도 고려해 볼 수 있습니다.

참고로, WEB API 2에 포함된 System.Net.Http.Formatting.JsonContractResolver는 Newtonsoft.Json.Serialization.DefaultContractResolver를 상속받은 것입니다.

JsonContractResolver
; https://learn.microsoft.com/en-us/previous-versions/aspnet/dn308832(v=vs.118)

대단하군요. ^^ System.Net 네임스페이스에 있는 타입이 상속받을 정도로 Json.NET 라이브러리가 그만큼 무시할 수 없는 인지도가 있다는!

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




마치기 전에, 여담 하나 이야기하자면.

저도 초보 시절에 응답 XML 데이터를 다음과 같은 식으로 정의한 적이 있었습니다.

<items>
    <csharp created="2017-05-06" />
    <visualbasic created="2017-05-07" />
</items>

그때 당시에 위의 XML 데이터를 보던 경력 개발자 한 분이 저에게 다음과 같은 식으로 바꿀 것을 제안했고,

<items>
    <item name="csharp" created="2017-05-06" />
    <item name="visualbasic" created="2017-05-07" />
</items>

너무나 타당한 그분의 의견에 수긍을 하고 바꾼 적이 있었습니다.

최근에 JSON으로 응답을 하는 몇몇 라이브러리들을 보다가... 저와 같은 실수를 하는 것을 보게 되는군요. ^^




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







[최초 등록일: ]
[최종 수정일: 6/12/2024]

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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  [113]  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11099정성태11/7/201630625.NET Framework: 620. C#에서 C/C++ 함수로 콜백 함수를 전달하는 예제 코드파일 다운로드1
11098정성태11/7/201619965오류 유형: 368. 빌드 이벤트에서 robocopy 사용 시 $(TargetDir) 매크로를 지정하는 경우 오류 발생
11097정성태11/7/201622894오류 유형: 367. go install: no install location for directory [...경로...] outside GOPATH
11096정성태11/6/201626694디버깅 기술: 83. PDB 파일을 수동으로 다운로드하는 방법
11095정성태11/6/201622944.NET Framework: 619. C# - Cognitive Services 중의 하나인 Face API를 사용해 얼굴 인식 및 흐림(blur) 효과 적용 [1]파일 다운로드1
11094정성태11/5/201624604VC++: 105. Visual Studio 2013/2015 - Ceemple OpenCV 확장을 이용한 웹캠 영상 출력
11093정성태11/4/201624501웹: 34. Edge 브라우저도 지원하는 클립보드 복사를 위한 자바스크립트 코드
11092정성태11/3/201631485.NET Framework: 618. C# - NAudio를 이용한 MP3 파일 재생 [5]파일 다운로드1
11091정성태11/3/201626275VC++: 104. std::call_once를 이용해 thread-safe한 Singleton 객체 생성파일 다운로드1
11090정성태11/1/201627729VC++: 103. C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드 [9]파일 다운로드1
11089정성태11/1/201626512디버깅 기술: 82. Windows 10을 위한 Symbol(PDB) 파일 내려받는 방법 [2]
11088정성태11/1/201630674.NET Framework: 617. C# - AForge.NET을 이용한 MP4 동영상 파일 재생 [7]파일 다운로드1
11087정성태11/1/201625071.NET Framework: 616. AForge.Video.FFMPEG를 최신 버전의 ffmpeg 파일로 의존성을 변경하는 방법파일 다운로드1
11086정성태11/1/201618921오류 유형: 366. The Microsoft Passport Container service terminated with the following error: General access denied error
11085정성태10/27/201633263.NET Framework: 615. C# - AForge.NET을 이용한 웹캠 영상 출력 [2]파일 다운로드1
11084정성태10/26/201621373오류 유형: 365. The User Profile Service service failed to the sign-in.
11083정성태10/26/201627845Windows: 131. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선 순위 조정 기능 [1]
11082정성태10/26/201629740.NET Framework: 614. C# - DateTime.Ticks의 정밀도 [4]파일 다운로드1
11081정성태10/26/201620275오류 유형: 364. You need to fix your Microsoft Account for apps on your other devices to be able to launch apps and continue experiences on this device.
11080정성태10/24/201623376Windows: 130. Windows Server 2016 Nano 서버 설치 방법
11079정성태10/21/201620532Windows: 129. Windows Server 2016 설치 CD에 있는 Convert-WindowsImage.ps1 사용 방법 정리
11078정성태10/21/201621859Windows: 128. Windows Server 2016 Nano 서버 VHD 이미지 만드는 방법 - TP5 기준
11077정성태10/21/201620368오류 유형: 363. Active Directory 서버의 NETLOGON 서비스가 멈췄을 때 발생하는 문제
11076정성태10/21/201619907오류 유형: 362. 윈도우 백업 시 오류 - 0x80780040
11075정성태10/20/201620887Windows: 127. Convert-WindowsImage.ps1 사용 방법 정리
11074정성태10/20/201629149Windows: 126. Windows Server 2016 평가판을 정식 버전으로 라이선스 변경하는 방법
... 106  107  108  109  110  111  112  [113]  114  115  116  117  118  119  120  ...