Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의 [링크 복사], [링크+제목 복사],
조회: 17094
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 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




System.Text.Json의 역직렬화 시 필드/속성 주의

다음은 간단한 System.Text.Json 예제입니다.

using System.Text.Json;

internal class Program
{
    private static void Main(string[] args)
    {
        string text = """
            {
                "id": "test",
                "data": [
                    {
                        "id": "test"
                    }
                ]
            }
            """;

        DataList? models = JsonSerializer.Deserialize<DataList>(text);
        Console.WriteLine(models?.data.Count);
    }
}

public class DataList
{
    public string id { get; set; } = "";
    public List<Data> data { get; set; } = new List<Data>();
}

public class Data
{
    public string id { get; set; } = "";
}

그런데, 무심코 이렇게 정의하면 안 됩니다. ^^;

public class DataList
{
    public string id { get; set; } = "";
    public List<Data> data;
}

그나마 위와 같이 하면 data.Count 접근 시 data가 null이어서 예외가 발생하는데요, 이것을 다음과 같이 바꾸면,

public class DataList
{
    public string id { get; set; } = "";
    public List<Data> data = new List<Data>();
}

data.Count에서 0이 나와 결과가 왜 저렇게 나오는지, 게다가 저게 하필 배열이라 뭔가 다른 방법이 있어야만 하는 것인지 자칫 (저처럼) 헤맬 수가 있습니다. 사실 저게 몇 개 안 되는 필드/멤버를 가진 경우에는 금방 표가 나서 쉽게 구분이 되지만 필드가 많아지면 쉽게 식별하지 못할 수 있습니다.

따라서, 처음 예제처럼 get/set 접근자를 사용하든가, 아니면 JsonInclude 특성을 포함하면 문제가 해결됩니다.

public class DataList
{
    public string id { get; set; } = "";

    [JsonInclude]
    public List<Data> data = new List<Data>();
}




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/8/2023]

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

비밀번호

댓글 작성자
 




... 151  152  153  154  [155]  156  157  158  159  160  161  162  163  164  165  ...
NoWriterDateCnt.TitleFile(s)
1292정성태5/24/201228612.NET Framework: 324. First-chance exception에 대해 조건에 따라 디버거가 멈추게 할 수는 없을까? [1]파일 다운로드1
1291정성태5/23/201236493VC++: 62. 배열 초기화를 위한 기계어 코드 확인 [2]
1290정성태5/18/201241027.NET Framework: 323. 관리자 권한이 필요한 작업을 COM+에 대행 [7]파일 다운로드1
1289정성태5/17/201246072.NET Framework: 322. regsvcs.exe로 어셈블리 등록 시 시스템 변경 사항 [5]파일 다운로드2
1288정성태5/17/201231729.NET Framework: 321. regasm.exe로 어셈블리 등록 시 시스템 변경 사항 (3) - Type Library파일 다운로드1
1287정성태5/17/201235086.NET Framework: 320. regasm.exe로 어셈블리 등록 시 시스템 변경 사항 (2) - .NET 4.0 + .NET 2.0 [2]
1286정성태5/17/201243885.NET Framework: 319. regasm.exe로 어셈블리 등록 시 시스템 변경 사항 (1) - .NET 2.0 + x86/x64/AnyCPU [5]
1285정성태5/16/201239239.NET Framework: 318. gacutil.exe로 어셈블리 등록 시 시스템 변경 사항파일 다운로드1
1284정성태5/15/201231239오류 유형: 155. Windows Phone 연결 상태에서 DRIVER POWER STATE FAILURE 블루 스크린 뜨는 현상
1283정성태5/12/201238784.NET Framework: 317. C# 관점에서의 Observer 패턴 구현 [1]파일 다운로드1
1282정성태5/12/201231890Phone: 6. Windows Phone 7 Silverlight에서 Google Map 사용하는 방법 [3]파일 다운로드1
1281정성태5/9/201239040.NET Framework: 316. WPF/Silverlight의 그래픽 단위와 Anti-aliasing 처리를 이해하자 [1]파일 다운로드1
1280정성태5/9/201231856오류 유형: 154. Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, ...'.
1279정성태5/9/201231521.NET Framework: 315. 해당 DLL이 Managed인지 / Unmanaged인지 확인하는 방법 [1]파일 다운로드1
1278정성태5/8/201232856오류 유형: 153. Visual Studio 디버깅 - Unable to break execution. This process is not currently executing the type of code that you selected to debug.
1277정성태5/8/201236872오류 유형: 152. cmd.exe - The system cannot write to the specified device. [2]
1276정성태4/28/201229074Phone: 5. 모든 Marketplace에 윈폰 앱을 등록하는 방법 [1]
1275정성태4/28/201232112개발 환경 구성: 150. 프로세스 실행으로 잠긴 파일이지만, 이름은 변경가능하다는 사실! 아셨나요? [7]
1274정성태4/17/201227165Phone: 4. "Holiday Calendar" 윈폰 응용 프로그램 등록
1273정성태4/6/201231061Phone: 3. 윈도우 폰을 위한 Holiyday Calendar 앱 개발파일 다운로드1
1272정성태4/5/201231994오류 유형: 151. ASP.NET - EcbGetUnicodeServerVariables 코드에서 System.AccessViolationException 예외 발생
1271정성태4/3/201233364Math: 6. 동전을 여러 더미로 나누는 경우의 수 세기 [1]
1270정성태3/29/201228709오류 유형: 150. Visual Studio 2010 원격 디버깅 오류 - Kerberos authentication failed
1269정성태3/27/201242970오류 유형: 149. ODP.NET 오류 - The provider is not compatible with the version of Oracle client
1268정성태3/27/201239029오류 유형: 148. WCF svc 호출 시 HTTP Error 404.17 - Not Found [1]
1267정성태3/16/201237787.NET Framework: 314. C++의 inline asm 사용을 .NET으로 포팅하는 방법 [1]파일 다운로드1
... 151  152  153  154  [155]  156  157  158  159  160  161  162  163  164  165  ...