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

... 31  32  33  34  35  36  37  38  39  [40]  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12936정성태1/22/202215359.NET Framework: 1138. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 멀티미디어 파일의 메타데이터를 보여주는 예제(metadata.c)파일 다운로드1
12935정성태1/22/202216039.NET Framework: 1137. ffmpeg의 파일 해시 예제(ffhash.c)를 C#으로 포팅파일 다운로드1
12934정성태1/22/202215462오류 유형: 788. Warning C6262 Function uses '65564' bytes of stack: exceeds /analyze:stacksize '16384'. Consider moving some data to heap. [2]
12933정성태1/21/202215938.NET Framework: 1136. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP2 오디오 파일 디코딩 예제(decode_audio.c)파일 다운로드1
12932정성태1/20/202217045.NET Framework: 1135. C# - ffmpeg(FFmpeg.AutoGen)로 하드웨어 가속기를 이용한 비디오 디코딩 예제(hw_decode.c) [2]파일 다운로드1
12931정성태1/20/202213559개발 환경 구성: 632. ASP.NET Core 프로젝트를 AKS/k8s에 올리는 과정
12930정성태1/19/202214802개발 환경 구성: 631. AKS/k8s의 Volume에 파일 복사하는 방법
12929정성태1/19/202214767개발 환경 구성: 630. AKS/k8s의 Pod에 Volume 연결하는 방법
12928정성태1/18/202214580개발 환경 구성: 629. AKS/Kubernetes에서 호스팅 중인 pod에 shell(/bin/bash)로 진입하는 방법
12927정성태1/18/202215109개발 환경 구성: 628. AKS 환경에 응용 프로그램 배포 방법
12926정성태1/17/202215022오류 유형: 787. AKS - pod 배포 시 ErrImagePull/ImagePullBackOff 오류
12925정성태1/17/202215675개발 환경 구성: 627. AKS의 준비 단계 - ACR(Azure Container Registry)에 docker 이미지 배포
12924정성태1/15/202217181.NET Framework: 1134. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) [2]파일 다운로드1
12923정성태1/15/202215971개발 환경 구성: 626. ffmpeg.exe를 사용해 비디오 파일을 MPEG1 포맷으로 변경하는 방법
12922정성태1/14/202214775개발 환경 구성: 625. AKS - Azure Kubernetes Service 생성 및 SLO/SLA 변경 방법
12921정성태1/14/202212525개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/202213844오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/202213376Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/202213841Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/202213030오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/202212317오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/202212915오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/202216125VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/202216552.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/202216525개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/202213016VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
... 31  32  33  34  35  36  37  38  39  [40]  41  42  43  44  45  ...