Microsoft MVP성태의 닷넷 이야기
.NET Framework: 351. JavaScriptSerializer, DataContractJsonSerializer, Json.NET [링크 복사], [링크+제목 복사],
조회: 25732
글쓴 사람
정성태 (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




JavaScriptSerializer, DataContractJsonSerializer, Json.NET


닷넷에는 기본적으로 JavaScriptSerializer, DataContractJsonSerializer 타입이 JSON 직렬화와 관련되어 제공됩니다. 각각 장단점이 있는데요. JavaScriptSerializer는 부가적인 작업 없이 모든 객체의 값을 Key/Value의 쌍으로 직렬화/역직렬화할 수 있습니다. 즉, strong-type이 제공되지 않습니다. 이를 보완하기 위해 클래스를 이용한 strong-type을 지원하는 DataContractJsonSerializer를 사용할 수 있는데, 당연히 클래스 구조는 그에 맞게 만들어 주어야 합니다.

예를 들어, 다음은 페이스북의 me 쿼리의 일부를 표현한 것인데요.

{
"id":"ttt",
"work":[
	{"employer":{"id":"zzz","name":"..."},
	 "start_date":"1992-01",
	}
],
"timezone":9,
"verified":true,
"updated_time":"2012-11-16T07:23:07+0000"
}

DataContractJsonSerializer로 역직렬화하기 위해 다음과 같이 클래스들을 만들어 주고,

public class GraphUser
{
    public string id { get; set; }

    public GraphWork[] work { get; set; }

    public int timezone { get; set; }
    public bool verified { get; set; }
    public string updated_time { get; set; }
}

public class GraphEmployer
{
    public string id { get; set; }
    public string name { get; set; }
}

public class GraphWork
{
    public GraphEmployer employer { get; set; }
    public string start_date { get; set; }
}

이렇게 코딩을 해주면 됩니다.

static void Main(string[] args)
{
    string json = "{ \"id\":\"ttt\", \"work\":[ 	{\"employer\":{\"id\":\"zzz\",\"name\":\"...\"},  \"start_date\":\"1992-01\" } ], \"timezone\":9, \"verified\":true, \"updated_time\":\"2012-11-16T07:23:07+0000\" }";

    DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(GraphUser));
    GraphUser user2 = dcjs.ReadObject(StringToStream(json)) as GraphUser;

    Console.WriteLine(user2.id);
    Console.WriteLine(user2.work[0].employer.id);
}




그런데, 여기서 문제가 있습니다. 만약 string 데이터에 "\n"를 포함하게 되면 DataContractJsonSerializer.ReadObject 호출 시에 예외가 발생합니다. 예를 들어, 위의 json 문자열의 id 값이 다음과 같은 경우입니다.

    string json = "{ \"id\":\"t\ntt\", ...[생략]... }";

그럼, 이런 예외 메시지가 발생합니다.

Unhandled Exception: System.Runtime.Serialization.SerializationException: Therewas an error deserializing the object of type ConsoleApplication1.GraphUser. Encountered invalid character ''. ---> System.FormatException: Encountered invalid character ''.
   at System.Runtime.Serialization.Json.XmlJsonReader.ComputeQuotedTextLengthUntilEndQuote(Byte[] buffer, Int32 offset, Int32 offsetMax, Boolean& escaped)
   at System.Runtime.Serialization.Json.XmlJsonReader.ReadQuotedText(Boolean moveToText)
   at System.Runtime.Serialization.Json.XmlJsonReader.Read()
   at System.Xml.XmlBaseReader.ReadElementContentAsString()
   at System.Runtime.Serialization.XmlReaderDelegator.ReadElementContentAsString()
   ...[생략]...
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(XmlDictionaryReader reader)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(Stream stream)
   at ConsoleApplication1.Program.Main(String[] args) in d:\...\Program.cs:line 28

문제의 원인은 "\n" 문자에서 역슬래시가 1개가 아닌 2개여야 한다는 점입니다. 그래서, 다음과 같이 변경해 주면 정상적으로 역직렬화를 합니다.

    string json = "{ \"id\":\"t\\ntt\", ...[생략]... }";

// 또는

    string json = "{ \"id\":\"t\\u000att\", ...[생략]... }";

그런데, 이런 경우가 왜 발생할까요? 물론 DataContractJsonSerializer로 직렬화했다면 저런 식으로 문자열이 나오지 않습니다. 제가 경험했던 곳은 바로 페이스북의 /me 쿼리에서 저런 결과를 볼 수 있었습니다. 따라서, 페이스북으로부터 json 문자열을 받는다면 반드시 '\n' 문자를 '\\n'으로 치환해 주는 작업이 선행되어야 합니다.




\n 문자에 대한 처리를 하지 않고 역직렬화를 하고 싶다면 Json.NET을 이용하면 됩니다. (다운로드 및 그에 대한 소스 코드는 모두 공개되어 있습니다.)

Json.NET
; http://json.codeplex.com/

Nuget을 지원하기 때문에 Visual Studio 2012에서 "View" / "Other Windows" / "Package Manager Console" 창을 띄우고, 다음과 같이 입력하면 Json.NET 이 프로젝트에 추가됩니다.

Package Manager Console Host Version 2.1.31002.9028

Type 'get-help NuGet' to see all available NuGet commands.

PM> Install-Package Newtonsoft.Json
Successfully installed 'Newtonsoft.Json 4.5.11'.
Successfully added 'Newtonsoft.Json 4.5.11' to ConsoleApplication1.

PM> 

다음은 Json.NET을 이용한 간단한 코드입니다.

string json = "{ \"id\":\"t\ntt\", \"work\":[ 	{\"employer\":{\"id\":\"zzz\",\"name\":\"...\"},  \"start_date\":\"1992-01\" } ], \"timezone\":9, \"verified\":true, \"updated_time\":\"2012-11-16T07:23:07+0000\" }";

GraphUser user = JsonConvert.DeserializeObject<GraphUser>(json);

Json.NET이 좋은 또 다른 이유가 하나 있습니다. 바로 DateTime 값의 역직렬화입니다. 예제의 json 문자열에 보면 updated_time의 값이 "2012-11-16T07:23:07+0000"인데 이를 그냥 "string" 타입으로 역직렬화하고 있지만, 만약 이 필드의 타입을 DateTime으로 바꾸게 되면,

public class GraphUser
{
    public string id { get; set; }

    public GraphWork[] work { get; set; }

    public int timezone { get; set; }
    public bool verified { get; set; }
    public DateTime updated_time { get; set; }
}

DataContractJsonSerializer으로 역직렬화하는 경우 다음과 같은 예외가 발생합니다.

There was an error deserializing the object of type ConsoleApplication1.GraphUser. DateTime content '2012-11-16T07:23:07+0000' does not start with '\/Date(' and end with ')\/' as required for JSON.


이런 상황에서 표준이냐 아니냐의 문제는 중요하지 않습니다. (그 유명한 페이스북에서 이런 식으로 데이터를 넘겨주기 때문에. ^^;)

하지만, 역시 이를 Json.NET으로 역직렬화하면 잘 됩니다. "2012-11-16T07:23:07+0000" UTC 시간이므로 변환하고 나면 한글 윈도우의 경우 +9 시간대를 적용받아 "{2012-11-16 16:23:07}" 값으로 계산합니다.

결론은, 3가지 Json 직렬화 방법 중에서 가능한 Json.NET을 이용하시는 것이 좋습니다. ^^
(첨부한 파일은 위의 간단한 코드를 담고 있는 테스트 프로젝트입니다.)




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







[최초 등록일: ]
[최종 수정일: 5/9/2024]

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

비밀번호

댓글 작성자
 



2012-12-21 11시20분
[lancers] 성능 문제도 있어요.
JSON.NET이 갑이었던 걸로 기억함...
[guest]
2012-12-22 12시22분
^^ 성능까지 좋았군요. 정보 감사드립니다.
정성태
2012-12-22 01시49분
[lancers] ASP.NET Web API에서 default json serializer를 아예 Json.net올 바꾼다고 했었는데, RTM에서도 유효한지 모르겠네요.
RC에서는 확실히 반영되어 있었습니다.
근데, 요즘 ASP.NET을 쓸 일이 없어서 확인을 못했네요.. ㅋㅋ
[guest]

... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13439정성태11/10/202311517닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/202311019닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/202311240닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/202311313닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/202310592닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/202310555스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20239392스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/202310200오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/202310744스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/202310941닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/202311081닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/202311220닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/202310724닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/202311236스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/202311104닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/202311001스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/202310761닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리 [1]
13421정성태10/4/202311024닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/202319259스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/202310859스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/202312482닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/202311784닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/202310380오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/202311815닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions) [2]
13414정성태9/16/202311146디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/202311968닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...