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

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://docs.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으로 응답을 하는 몇몇 라이브러리들을 보다가... 저와 같은 실수를 하는 것을 보게 되는군요. ^^




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







[최초 등록일: ]
[최종 수정일: 7/13/2021]

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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
11842정성태3/13/201910232개발 환경 구성: 433. 마이크로소프트의 CoreCLR 프로파일러 예제를 Visual Studio CMake로 빌드하는 방법 [1]파일 다운로드1
11841정성태3/13/201910211VS.NET IDE: 132. Visual Studio 2019 - CMake의 컴파일러를 기본 g++에서 clang++로 변경
11840정성태3/13/201911307오류 유형: 526. 윈도우 10 Ubuntu App 환경에서는 USB 외장 하드 접근 불가
11839정성태3/12/201914045디버깅 기술: 124. .NET Core 웹 앱을 호스팅하는 Azure App Services의 프로세스 메모리 덤프 및 windbg 분석 개요 [3]
11838정성태3/7/201916831.NET Framework: 811. (번역글) .NET Internals Cookbook Part 1 - Exceptions, filters and corrupted processes [1]파일 다운로드1
11837정성태3/6/201926426기타: 74. 도서: 시작하세요! C# 7.3 프로그래밍 [10]
11836정성태3/5/201914377오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201914129.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201913030개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201913781개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201910821오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201910411오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201910206오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201912115개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201918502개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201912395오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201912277오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201917144개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201911950오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201913425오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201911563오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201912037오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201915174오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201913834Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201912751VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/20199923오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...