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)
11257정성태7/31/201719869.NET Framework: 667. bypassTrustedAppStrongNames 옵션 설명파일 다운로드1
11256정성태7/25/201721794디버깅 기술: 90. windbg의 lm 명령으로 보이지 않는 .NET 4.0 ClassLibrary를 명시적으로 로드하는 방법 [1]
11255정성태7/18/201724299디버깅 기술: 89. Win32 Debug CRT Heap Internals의 0xBAADF00D 표시 재현 [1]파일 다운로드3
11254정성태7/17/201720719개발 환경 구성: 322. "Visual Studio Emulator for Android" 에뮬레이터를 "Android Studio"와 함께 쓰는 방법
11253정성태7/17/201721349Math: 21. "Coding the Matrix" 문제 2.5.1 풀이 [1]파일 다운로드1
11252정성태7/13/201719092오류 유형: 411. RTVS 또는 PTVS 실행 시 Could not load type 'Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowFactory2'
11251정성태7/13/201718560디버깅 기술: 88. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 (2)
11250정성태7/13/201722180디버깅 기술: 87. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 [1]
11249정성태7/12/201719897오류 유형: 410. LoadLibrary("[...].dll") failed - The specified procedure could not be found.
11248정성태7/12/201726466오류 유형: 409. pip install pefile - 'cp949' codec can't decode byte 0xe2 in position 208687: illegal multibyte sequence
11247정성태7/12/201720766오류 유형: 408. SqlConnection 객체 생성 시 무한 대기 문제파일 다운로드1
11246정성태7/11/201718812VS.NET IDE: 118. Visual Studio - 다중 폴더에 포함된 파일들에 대한 "Copy to Output Directory"를 한 번에 설정하는 방법
11245정성태7/10/201724603개발 환경 구성: 321. Visual Studio Emulator for Android 소개 [2]
11244정성태7/10/201724768오류 유형: 407. Visual Studio에서 ASP.NET Core 실행할 때 dotnet.exe 프로세스의 -532462766 오류 발생 [1]
11243정성태7/10/201721560.NET Framework: 666. dotnet.exe - 윈도우 운영체제에서의 .NET Core 버전 찾기 규칙
11242정성태7/8/201721095제니퍼 .NET: 27. 제니퍼 닷넷 적용 사례 (7) - 노후된 스토리지 장비로 인한 웹 서비스 Hang (멈춤) 현상
11241정성태7/8/201719761오류 유형: 406. Xamarin 빌드 에러 XA5209, APT0000
11240정성태7/7/201723564.NET Framework: 665. ClickOnce를 웹 브라우저를 이용하지 않고 쿼리 문자열을 전달하면서 실행하는 방법 [3]파일 다운로드1
11239정성태7/6/201724191.NET Framework: 664. Protocol Handler - 웹 브라우저에서 데스크톱 응용 프로그램을 실행하는 방법 [5]파일 다운로드1
11238정성태7/6/201721694오류 유형: 405. NT 서비스 시작 시 "Error 1067: The process terminated unexpectedly." 오류 발생 [2]
11237정성태7/5/201723376.NET Framework: 663. C# - PDB 파일 경로를 PE 파일로부터 얻는 방법파일 다운로드1
11236정성태7/4/201727082.NET Framework: 662. C# - VHD/VHDX 가상 디스크를 마운트하지 않고 파일을 복사하는 방법파일 다운로드1
11235정성태6/29/201721274Math: 20. Matlab/Octave로 Gram-Schmidt 정규 직교 집합 구하는 방법
11234정성태6/29/201718797오류 유형: 404. SharePoint 2013 설치 과정에서 "The username is invalid The account must be a valid domain account" 오류 발생
11233정성태6/28/201718676오류 유형: 403. SharePoint Server 2013을 Windows Server 2016에 설치할 때 .NET 4.5 설치 오류 발생
11232정성태6/28/201719585Windows: 144. Windows Server 2016에 Windows Identity Extensions을 설치하는 방법
... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...