[C#/COMMON/.NET5] HttpRequestMessage 클래스 : POST 요청 열거 가능형 구하기
■ HttpRequestMessage 클래스를 사용해 POST 요청 열거 가능형을 구하는 방법을 보여준다. ▶ HttpRequestMessage 클래스 : POST 요청 열거 가능형 구하기 예제 (C#)
■ HttpRequestMessage 클래스를 사용해 POST 요청 열거 가능형을 구하는 방법을 보여준다. ▶ HttpRequestMessage 클래스 : POST 요청 열거 가능형 구하기 예제 (C#)
■ jsonEncode 함수를 사용해 객체에서 JSON 문자열을 구하는 방법을 보여준다. ▶ 예제 코드 (DART)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import 'dart:convert'; void main() { List<Map<String, Object?>> scoreList = [ { 'score': 40 }, { 'score': 80 }, { 'score': 100, 'overtime': true, 'special_guest': null } ]; String jsonString = jsonEncode(scoreList); print(jsonString); } |
■ jsonDecode 함수를 사용해 JSON 문자열에서 객체를 생성하는 방법을 보여준다. ▶ 예제 코드 (DART)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import 'dart:convert'; void main() { String jsonString = ''' [ { "subject" : "국어", "score" : 100 }, { "subject" : "수학", "score" : 90 } ] '''; dynamic recordList = jsonDecode(jsonString); print(recordList is List); dynamic record1 = recordList[0]; print(record1 is Map); print(record1['subject']); print(record1['score']); dynamic record2 = recordList[1]; print(record2 is Map); print(record2['subject']); print(record2['score']); } |
■ .NET Newtonsoft.Json을 사용해 JSON 파일을 파싱하는 방법을 보여준다. ▶ setting.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{ "MainFormLeft" : 52, "MainFormTop" : 52, "MainFormWidth" : 920, "MainFormHeight" : 690, "MainFormState" : "Maximized", "SkinStyle" : "The Bezier", "RibbonMinimized" : true, "SidebarStyle" : "NavigationPane", "SidebarWidth" : 100, "SidebarCollapsable" : false, "SidebarVisible" : true } |
▶ 실행 명령
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$JSON = (Get-Content "d:\setting.json" -Encoding UTF8 | Out-String) [Reflection.Assembly]::LoadFile("d:\Newtonsoft.Json.dll") $Setting = [Newtonsoft.Json.Linq.JObject]::Parse($JSON) $Setting.Item("MainFormLeft" ).ToString() $Setting.Item("MainFormTop" ).ToString() $Setting.Item("MainFormWidth" ).ToString() $Setting.Item("MainFormHeight" ).ToString() $Setting.Item("MainFormState" ).ToString() $Setting.Item("SkinStyle" ).ToString() $Setting.Item("RibbonMinimized" ).ToString() $Setting.Item("SidebarStyle" ).ToString() $Setting.Item("SidebarWidth" ).ToString() $Setting.Item("SidebarCollapsable").ToString() $Setting.Item("SidebarVisible" ).ToString() |
Newtonsoft.Json.zip
■ ConvertFrom-Json 명령을 사용해 JSON 파일을 파싱하는 방법을 보여준다. ▶ setting.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{ "MainFormLeft" : 52, "MainFormTop" : 52, "MainFormWidth" : 920, "MainFormHeight" : 690, "MainFormState" : "Maximized", "SkinStyle" : "The Bezier", "RibbonMinimized" : true, "SidebarStyle" : "NavigationPane", "SidebarWidth" : 100, "SidebarCollapsable" : false, "SidebarVisible" : true } |
▶ 실행 명령
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$JSON = (Get-Content "d:\test.json" -Encoding UTF8 | Out-String) $Setting = ConvertFrom-Json $JSON $Setting.MainFormLeft $Setting.MainFormTop $Setting.MainFormWidth $Setting.MainFormHeight $Setting.MainFormState $Setting.SkinStyle $Setting.RibbonMinimized $Setting.SidebarStyle $Setting.SidebarWidth $Setting.SidebarCollapsable $Setting.SidebarVisible |
■ JSON 문자열에서 JSON 클래스를 생성하는 방법을 보여준다. [TestLibrary 프로젝트] ▶ JSONValueType.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
namespace TestLibrary { /// <summary> /// JSON 값 타입 /// </summary> public enum JSONValueType { /// <summary> /// ANYTHING /// </summary> Anything, /// <summary> /// 문자열 /// </summary> String, /// <summary> /// 진리값 /// </summary> Boolean, /// <summary> /// 정수 /// </summary> Integer, /// <summary> /// 배정도 정수 /// </summary> Long, /// <summary> /// 부동형 실수 /// </summary> Float, /// <summary> /// 날짜 /// </summary> Date, /// <summary> /// NULL 가능 정수 /// </summary> NullableInteger, /// <summary> /// NULL 가능 배정도 정수 /// </summary> NullableLong, /// <summary> /// NULL 가능 부동형 실수 /// </summary> NullableFloat, /// <summary> /// NULL 가능 진리값 /// </summary> NullableBoolean, /// <summary> /// NULL 가능 날짜 /// </summary> NullableDate, /// <summary> /// 객체 /// </summary> Object, /// <summary> /// 배열 /// </summary> Array, /// <summary> /// 딕셔너리 /// </summary> Dictionary, /// <summary> /// NULL 가능 SOMETHING /// </summary> NullableSomething, /// <summary> /// 제약 없음 /// </summary> NonConstrained } } |
▶ JSONType.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace TestLibrary { /// <summary> /// JSON 타입 /// </summary> public class JSONType { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 제너레이터 /// </summary> private IJSONClassGenerator generator; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 값 타입 - ValueType /// <summary> /// 값 타입 /// </summary> public JSONValueType ValueType { get; private set; } #endregion #region 내부 타입 - InternalType /// <summary> /// 내부 타입 /// </summary> public JSONType InternalType { get; private set; } #endregion #region 할당명 - AssignedName /// <summary> /// 할당명 /// </summary> public string AssignedName { get; private set; } #endregion #region 캐시 필수 여부 - MustCache /// <summary> /// 캐시 필수 여부 /// </summary> public bool MustCache { get { switch(ValueType) { case JSONValueType.Array : return true; case JSONValueType.Object : return true; case JSONValueType.Anything : return true; case JSONValueType.Dictionary : return true; case JSONValueType.NonConstrained : return true; default : return false; } } } #endregion #region 필드 정보 리스트 - FieldInfoList /// <summary> /// 필드 정보 리스트 /// </summary> public IList<FieldInfo> FieldInfoList { get; internal set; } #endregion #region 루트 여부 - IsRoot /// <summary> /// 루트 여부 /// </summary> public bool IsRoot { get; internal set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - JSONType(generator, token) /// <summary> /// 생성자 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="token">토큰</param> public JSONType(IJSONClassGenerator generator, JToken token) : this(generator) { ValueType = GetFirstValueType(token); if(ValueType == JSONValueType.Array) { JArray array = (JArray)token; InternalType = GetCommonType(generator, array.ToArray()); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Internal #region 생성자 - JSONType(generator, type) /// <summary> /// 생성자 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="type">타입</param> internal JSONType(IJSONClassGenerator generator, JSONValueType type) : this(generator) { ValueType = type; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 생성자 - JSONType(generator) /// <summary> /// 생성자 /// </summary> /// <param name="generator">JSON 클래스 제너레이터 인터페이스</param> private JSONType(IJSONClassGenerator generator) { this.generator = generator; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 공통 타입 구하기 - GetCommonType(generator, tokenArray) /// <summary> /// 공통 타입 구하기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="tokenArray">토큰 배열</param> /// <returns>공통 타입 </returns> public static JSONType GetCommonType(IJSONClassGenerator generator, JToken[] tokenArray) { if(tokenArray.Length == 0) { return new JSONType(generator, JSONValueType.NonConstrained); } JSONType commonType = new JSONType(generator, tokenArray[0]).MaybeMakeNullable(generator); for(int i = 1; i < tokenArray.Length; i++) { JSONType currentType = new JSONType(generator, tokenArray[i]); commonType = commonType.GetCommonType(currentType); } return commonType; } #endregion //////////////////////////////////////////////////////////////////////////////// Internal #region NULL 구하기 - GetNull(generator) /// <summary> /// NULL 구하기 /// </summary> /// <param name="generator">제너레이터</param> /// <returns>NULL</returns> internal static JSONType GetNull(IJSONClassGenerator generator) { return new JSONType(generator, JSONValueType.NullableSomething); } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 첫번째 값 타입 구하기 - GetFirstValueType(token) /// <summary> /// 첫번째 값 타입 구하기 /// </summary> /// <param name="token">토큰</param> /// <returns>첫번째 값 타입</returns> private static JSONValueType GetFirstValueType(JToken token) { JTokenType type = token.Type; if(type == JTokenType.Integer) { if((long)((JValue)token).Value < int.MaxValue) { return JSONValueType.Integer; } else { return JSONValueType.Long; } } switch(type) { case JTokenType.Array : return JSONValueType.Array; case JTokenType.Boolean : return JSONValueType.Boolean; case JTokenType.Float : return JSONValueType.Float; case JTokenType.Null : return JSONValueType.NullableSomething; case JTokenType.Undefined : return JSONValueType.NullableSomething; case JTokenType.String : return JSONValueType.String; case JTokenType.Object : return JSONValueType.Object; case JTokenType.Date : return JSONValueType.Date; default : return JSONValueType.Anything; } } #endregion #region NULL 여부 구하기 - IsNull(valueType) /// <summary> /// NULL 여부 구하기 /// </summary> /// <param name="valueType">값 타입</param> /// <returns>NULL 여부</returns> private static bool IsNull(JSONValueType valueType) { return valueType == JSONValueType.NullableSomething; } #endregion #region NULL 여부 구하기 - IsNull(tokenType) /// <summary> /// NULL 여부 구하기 /// </summary> /// <param name="tokenType">토큰 타입</param> /// <returns>NULL 여부</returns> private static bool IsNull(JTokenType tokenType) { return tokenType == JTokenType.Null || tokenType == JTokenType.Undefined; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Public #region 공통 타입 구하기 - GetCommonType(type) /// <summary> /// 공통 타입 구하기 /// </summary> /// <param name="type">타입</param> /// <returns>공통 타입</returns> public JSONType GetCommonType(JSONType type) { JSONValueType commonValueType = GetCommonValueType(ValueType, type.ValueType); if(commonValueType == JSONValueType.Array) { if(type.ValueType == JSONValueType.NullableSomething) { return this; } if(ValueType == JSONValueType.NullableSomething) { return type; } JSONType commonInternalType = InternalType.GetCommonType(type.InternalType).MaybeMakeNullable(generator); if(commonInternalType != InternalType) { return new JSONType(generator, JSONValueType.Array) { InternalType = commonInternalType }; } } if(ValueType == commonValueType) { return this; } return new JSONType(generator, commonValueType).MaybeMakeNullable(generator); } #endregion #region 명칭 할당하기 - AssignName(name) /// <summary> /// 명칭 할당하기 /// </summary> /// <param name="name">명칭</param> public void AssignName(string name) { AssignedName = name; } #endregion #region 렌더링 명칭 구하기 - GetReaderName() /// <summary> /// 렌더링 명칭 구하기 /// </summary> /// <returns>렌더링 명칭</returns> public string GetReaderName() { if(ValueType == JSONValueType.Anything || ValueType == JSONValueType.NullableSomething || ValueType == JSONValueType.NonConstrained) { return "ReadObject"; } if(ValueType == JSONValueType.Object) { return string.Format("ReadStronglyTypedObject<{0}>", AssignedName); } else if(ValueType == JSONValueType.Array) { return string.Format("ReadArray<{0}>", InternalType.GetTypeName()); } else { return string.Format("Read{0}", Enum.GetName(typeof(JSONValueType), ValueType)); } } #endregion #region 내면 유형 구하기 - GetInnermostType() /// <summary> /// 내면 유형 구하기 /// </summary> /// <returns>내면 유형</returns> public JSONType GetInnermostType() { if(ValueType != JSONValueType.Array) { throw new InvalidOperationException(); } if(InternalType.ValueType != JSONValueType.Array) { return InternalType; } return InternalType.GetInnermostType(); } #endregion #region 타입명 구하기 - GetTypeName() /// <summary> /// 타입명 구하기 /// </summary> /// <returns>타입명</returns> public string GetTypeName() { return this.generator.CodeWriter.GetTypeName(this, this.generator); } #endregion #region JSON 토큰 타입 구하기 - GetJTokenType() /// <summary> /// JSON 토큰 타입 구하기 /// </summary> /// <returns>JSON 토큰 타입</returns> public string GetJTokenType() { switch(ValueType) { case JSONValueType.Boolean : case JSONValueType.Integer : case JSONValueType.Long : case JSONValueType.Float : case JSONValueType.Date : case JSONValueType.NullableBoolean : case JSONValueType.NullableInteger : case JSONValueType.NullableLong : case JSONValueType.NullableFloat : case JSONValueType.NullableDate : case JSONValueType.String : return "JValue"; case JSONValueType.Array : return "JArray"; case JSONValueType.Dictionary : return "JObject"; case JSONValueType.Object : return "JObject"; default : return "JToken"; } } #endregion //////////////////////////////////////////////////////////////////////////////// Internal #region 혹시나 NULL 가능 만들기 - MaybeMakeNullable(generator) /// <summary> /// 혹시나 NULL 가능 만들기 /// </summary> /// <param name="generator">제너레이터</param> /// <returns>JSON 타입</returns> internal JSONType MaybeMakeNullable(IJSONClassGenerator generator) { if(!generator.AlwaysUseNullableValues) { return this; } return GetCommonType(JSONType.GetNull(generator)); } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region 공통 값 타입 구하기 - GetCommonValueType(valueType1, valueType2) /// <summary> /// 공통 값 타입 구하기 /// </summary> /// <param name="valueType1">값 타입 1</param> /// <param name="valueType2">값 타입 2</param> /// <returns>공통 값 타입</returns> private JSONValueType GetCommonValueType(JSONValueType valueType1, JSONValueType valueType2) { if(valueType1 == JSONValueType.NonConstrained) { return valueType2; } if(valueType2 == JSONValueType.NonConstrained) { return valueType1; } switch(valueType1) { case JSONValueType.Boolean : if(IsNull(valueType2)) { return JSONValueType.NullableBoolean; } if(valueType2 == JSONValueType.Boolean) { return valueType1; } break; case JSONValueType.NullableBoolean : if(IsNull(valueType2)) { return valueType1; } if(valueType2 == JSONValueType.Boolean) { return valueType1; } break; case JSONValueType.Integer : if(IsNull(valueType2)) { return JSONValueType.NullableInteger; } if(valueType2 == JSONValueType.Float) { return JSONValueType.Float; } if(valueType2 == JSONValueType.Long) { return JSONValueType.Long; } if(valueType2 == JSONValueType.Integer) { return valueType1; } break; case JSONValueType.NullableInteger : if(IsNull(valueType2)) { return valueType1; } if(valueType2 == JSONValueType.Float) { return JSONValueType.NullableFloat; } if(valueType2 == JSONValueType.Long) { return JSONValueType.NullableLong; } if(valueType2 == JSONValueType.Integer) { return valueType1; } break; case JSONValueType.Float : if(IsNull(valueType2)) { return JSONValueType.NullableFloat; } if(valueType2 == JSONValueType.Float) { return valueType1; } if(valueType2 == JSONValueType.Integer) { return valueType1; } if(valueType2 == JSONValueType.Long) { return valueType1; } break; case JSONValueType.NullableFloat : if(IsNull(valueType2)) { return valueType1; } if(valueType2 == JSONValueType.Float) { return valueType1; } if(valueType2 == JSONValueType.Integer) { return valueType1; } if(valueType2 == JSONValueType.Long) { return valueType1; } break; case JSONValueType.Long : if(IsNull(valueType2)) { return JSONValueType.NullableLong; } if(valueType2 == JSONValueType.Float) { return JSONValueType.Float; } if(valueType2 == JSONValueType.Integer) { return valueType1; } break; case JSONValueType.NullableLong : if(IsNull(valueType2)) { return valueType1; } if(valueType2 == JSONValueType.Float) { return JSONValueType.NullableFloat; } if(valueType2 == JSONValueType.Integer) { return valueType1; } if(valueType2 == JSONValueType.Long) { return valueType1; } break; case JSONValueType.Date : if(IsNull(valueType2)) { return JSONValueType.NullableDate; } if(valueType2 == JSONValueType.Date) { return JSONValueType.Date; } break; case JSONValueType.NullableDate : if(IsNull(valueType2)) { return valueType1; } if(valueType2 == JSONValueType.Date) { return valueType1; } break; case JSONValueType.NullableSomething : if(IsNull(valueType2)) { return valueType1; } if(valueType2 == JSONValueType.String) { return JSONValueType.String; } if(valueType2 == JSONValueType.Integer) { return JSONValueType.NullableInteger; } if(valueType2 == JSONValueType.Float) { return JSONValueType.NullableFloat; } if(valueType2 == JSONValueType.Long) { return JSONValueType.NullableLong; } if(valueType2 == JSONValueType.Boolean) { return JSONValueType.NullableBoolean; } if(valueType2 == JSONValueType.Date) { return JSONValueType.NullableDate; } if(valueType2 == JSONValueType.Array) { return JSONValueType.Array; } if(valueType2 == JSONValueType.Object) { return JSONValueType.Object; } break; case JSONValueType.Object : if(IsNull(valueType2)) { return valueType1; } if(valueType2 == JSONValueType.Object) { return valueType1; } if(valueType2 == JSONValueType.Dictionary) { throw new ArgumentException(); } break; case JSONValueType.Dictionary : throw new ArgumentException(); case JSONValueType.Array : if(IsNull(valueType2)) { return valueType1; } if(valueType2 == JSONValueType.Array) { return valueType1; } break; case JSONValueType.String : if(IsNull(valueType2)) { return valueType1; } if(valueType2 == JSONValueType.String) { return valueType1; } break; } return JSONValueType.Anything; } #endregion } } |
▶ FieldInfo.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; namespace TestLibrary { /// <summary> /// 필드 정보 /// </summary> public class FieldInfo { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 제너레이터 /// </summary> private IJSONClassGenerator generator; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 멤버명 - MemberName /// <summary> /// 멤버명 /// </summary> public string MemberName { get; private set; } #endregion #region JSON 멤버명 - JSONMemberName /// <summary> /// JSON 멤버명 /// </summary> public string JSONMemberName { get; private set; } #endregion #region 타입 - Type /// <summary> /// 타입 /// </summary> public JSONType Type { get; private set; } #endregion #region 예제 리스트 - ExampleList /// <summary> /// 예제 리스트 /// </summary> public IList<object> ExampleList { get; private set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - FieldInfo(generator, jsonMemberName, type, usePascalCase, exampleList) /// <summary> /// 생성자 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="jsonMemberName">JSON 멤버명</param> /// <param name="type">타입</param> /// <param name="usePascalCase">파스칼 표기법 사용 여부</param> /// <param name="exampleList">예제 리스트</param> public FieldInfo(IJSONClassGenerator generator, string jsonMemberName, JSONType type, bool usePascalCase, IList<object> exampleList) { this.generator = generator; JSONMemberName = jsonMemberName; MemberName = jsonMemberName; if(usePascalCase) { MemberName = JSONClassGenerator.ToTitleCase(MemberName); } Type = type; ExampleList = exampleList; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성 코드 구하기 - GetGenerationCode(source) /// <summary> /// 생성 코드 구하기 /// </summary> /// <param name="source">소스 문자열</param> /// <returns>생성 코드</returns> public string GetGenerationCode(string source) { FieldInfo fieldInfo = this; if(fieldInfo.Type.ValueType == JSONValueType.Array) { JSONType innermostType = fieldInfo.Type.GetInnermostType(); return string.Format ( "({1})JsonClassHelper.ReadArray<{5}>(JsonClassHelper.GetJToken<JArray>({0}, \"{2}\"), JsonClassHelper.{3}, typeof({6}))", source, fieldInfo.Type.GetTypeName(), fieldInfo.JSONMemberName, innermostType.GetReaderName(), -1, innermostType.GetTypeName(), fieldInfo.Type.GetTypeName() ); } else if(fieldInfo.Type.ValueType == JSONValueType.Dictionary) { return string.Format ( "({1})JsonClassHelper.ReadDictionary<{2}>(JsonClassHelper.GetJToken<JObject>({0}, \"{3}\"))", source, fieldInfo.Type.GetTypeName(), fieldInfo.Type.InternalType.GetTypeName(), fieldInfo.JSONMemberName, fieldInfo.Type.GetTypeName() ); } else { return string.Format ( "JsonClassHelper.{1}(JsonClassHelper.GetJToken<{2}>({0}, \"{3}\"))", source, fieldInfo.Type.GetReaderName(), fieldInfo.Type.GetJTokenType(), fieldInfo.JSONMemberName ); } } #endregion #region 예제 텍스트 구하기 - GetExampleText() /// <summary> /// 예제 텍스트 구하기 /// </summary> /// <returns>예제 텍스트</returns> public string GetExampleText() { return string.Join(", ", ExampleList.Take(5).Select(x => JsonConvert.SerializeObject(x)).ToArray()); } #endregion } } |
▶ ICodeWriter.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
using System.IO; namespace TestLibrary { /// <summary> /// 코드 작성자 인터페이스 /// </summary> public interface ICodeWriter { //////////////////////////////////////////////////////////////////////////////////////////////////// Property #region 파일 확장자 - FileExtension /// <summary> /// 파일 확장자 /// </summary> string FileExtension { get; } #endregion #region 디스플레이명 - DisplayName /// <summary> /// 디스플레이명 /// </summary> string DisplayName { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method #region 타입명 구하기 - GetTypeName(type, generator) /// <summary> /// 타입명 구하기 /// </summary> /// <param name="type">타입</param> /// <param name="generator">제너레이터</param> /// <returns>타입명</returns> string GetTypeName(JSONType type, IJSONClassGenerator generator); #endregion #region 클래스 쓰기 - WriteClass(generator, writer, type) /// <summary> /// 클래스 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="type">타입</param> void WriteClass(IJSONClassGenerator generator, TextWriter writer, JSONType type); #endregion #region 파일 시작 쓰기 - WriteFileStart(generator, writer) /// <summary> /// 파일 시작 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> void WriteFileStart(IJSONClassGenerator generator, TextWriter writer); #endregion #region 파일 종료 쓰기 - WriteFileEnd(generator, writer) /// <summary> /// 파일 종료 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> void WriteFileEnd(IJSONClassGenerator generator, TextWriter writer); #endregion #region 네임스페이스 시작 쓰기 - WriteNamespaceStart(generator, writer, root) /// <summary> /// 네임스페이스 시작 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="root">루트 여부</param> void WriteNamespaceStart(IJSONClassGenerator generator, TextWriter writer, bool root); #endregion #region 네임스페이스 종료 쓰기 - WriteNamespaceEnd(generator, writer, root) /// <summary> /// 네임스페이스 종료 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="root">루트 여부</param> void WriteNamespaceEnd(IJSONClassGenerator generator, TextWriter writer, bool root); #endregion } } |
■ JsonConfigurationExtensions 클래스의 AddJsonFile 확장 메소드를 사용해 JSON 구성 공급자를 등록하는 방법을 보여준다. ▶ sample.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "TestKey" : "TestValue2", "Position" : { "Title" : "Editor2", "Name" : "Smith2" }, "Logging" : { "LogLevel" : { "Default" : "Information", "Microsoft" : "Warning", "Microsoft.Hosting.Lifetime" : "Information" } }, "AllowedHosts" : "*" } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; namespace TestProject { /// <summary> /// 프로그램 /// </summary> public class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 프로그램 시작하기 - Main(argumentArray) /// <summary> /// 프로그램 시작하기 /// </summary> /// <param name="argumentArray">인자 배열</param> public static void Main(string[] argumentArray) { CreateHostBuilder(argumentArray).Build().Run(); } #endregion #region 호스트 빌더 생성하기 - CreateHostBuilder(argumentArray) /// <summary> /// 호스트 빌더 생성하기 /// </summary> /// <param name="argumentArray">인자 배열</param> /// <returns>호스트 빌더</returns> public static IHostBuilder CreateHostBuilder(string[] argumentArray) => Host.CreateDefaultBuilder(argumentArray) .ConfigureAppConfiguration ( (context, configuration) => { var environment = context.HostingEnvironment; configuration.AddJsonFile ( "sample.json", optional : true, reloadOnChange : true ); configuration.AddJsonFile ( $"sample.{environment.EnvironmentName}.json", optional : true, reloadOnChange : true ); configuration.AddEnvironmentVariables(); if(argumentArray != null) { configuration.AddCommandLine(argumentArray); } } ) .ConfigureWebHostDefaults ( builder => { builder.UseStartup<Startup>(); } ); #endregion } } |
▶ appsettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
{ "TestKey" : "TestValue1", "Position" : { "Title" : "Editor1", "Name" : "Smith1" }, "Logging" : { "LogLevel" : { "Default" : "Information", "Microsoft" : "Warning", "Microsoft.Hosting.Lifetime" : "Information" } }, "AllowedHosts" : "*" } |
■ NewtonsoftJsonMvcBuilderExtensions 클래스의 AddNewtonsoftJson 확장 메소드를 사용해 카멜 표기법으로 JSON 문자열을 구하는 방법을 보여준다. ▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Newtonsoft.Json.Serialization; namespace TestProject { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public IConfiguration Configuration { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Startup(configuration) /// <summary> /// 생성자 /// </summary> /// <param name="configuration">구성</param> public Startup(IConfiguration configuration) { Configuration = configuration; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(services) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="services">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson ( options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } ); } #endregion #region 구성하기 - Configure(app, environment) /// <summary> /// 구성하기 /// </summary> /// <param name="app">애플리케이션 빌더</param> /// <param name="environment">웹 호스트 환경</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment environment) { if(environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints ( endpoints => { endpoints.MapControllers(); } ); } #endregion } } |
※ JSON 문자열 변환시 카멜
■ Microsoft.AspNetCore.Mvc.NewtonsoftJson 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ JSON 압축 스트리밍 데이터를 구하는 방법을 보여준다. [TestServer 프로젝트] ▶ IDataService.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System.IO; using System.ServiceModel; namespace TestServer { /// <summary> /// 데이터 서비스 인터페이스 /// </summary> [ServiceContract] public interface IDataService { //////////////////////////////////////////////////////////////////////////////////////////////////// Method #region 데이터 구하기 - GetData(dataID, conditionData) /// <summary> /// 데이터 구하기 /// </summary> /// <param name="dataID">데이터 ID</param> /// <param name="conditionData">조건 데이터</param> /// <returns>데이터</returns> [OperationContract] Stream GetData(string dataID, string conditionData); #endregion } } |
▶ DataService.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.ServiceModel; using TestCommon; namespace TestServer { /// <summary> /// 데이터 서비스 /// </summary> public class DataService : IDataService { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 임시 디렉토리 경로 /// </summary> private const string TEMPORARY_DIRECTORY_PATH = "d:\\temporary_server"; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 데이터 구하기 - GetData(dataID, conditionData) /// <summary> /// 데이터 구하기 /// </summary> /// <param name="dataID">데이터 ID</param> /// <param name="conditionData">조건 데이터</param> /// <returns>데이터</returns> public Stream GetData(string dataID, string conditionData) { WriteMessage("START GET DATA"); WriteMessage("DATA ID : {0}", dataID); WriteMessage("CONDITION DATA"); WriteMessage("--------------------------------------------------"); WriteMessage(conditionData); WriteMessage("--------------------------------------------------"); string transactionID = GUIDHelper.GetGUID(); if(!Directory.Exists(TEMPORARY_DIRECTORY_PATH)) { Directory.CreateDirectory(TEMPORARY_DIRECTORY_PATH); } ////////////////////////////////////////////////// int dataCount = JSONHelper.Deserialize<int>(conditionData); List<Student> list = Student.GetData(dataCount); ////////////////////////////////////////////////// WriteMessage("START CREATE TRANSACTION FILE"); string transactionFilePath = Path.Combine(TEMPORARY_DIRECTORY_PATH, string.Format("{0}.dat", transactionID)); using(FileStream fileStream = new FileStream(transactionFilePath, FileMode.Create, FileAccess.Write)) { using(GZipStream gZipStream = new GZipStream(fileStream, CompressionMode.Compress)) { JSONHelper.Serialize(list, gZipStream); } } WriteMessage("END CREATE TRANSACTION FILE"); Stream stream = null; try { stream = File.Open(transactionFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch { } OperationContext operationContext = OperationContext.Current; operationContext.OperationCompleted += delegate(object sender, EventArgs e) { try { File.Delete(transactionFilePath); } catch { } }; WriteMessage("END GET DATA"); return stream; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 메시지 쓰기 - WriteMessage(format, parameterArray) /// <summary> /// 메시지 쓰기 /// </summary> /// <param name="format">포맷 문자열</param> /// <param name="parameterArray">매개 변수 배열</param> private void WriteMessage(string format, params object[] parameterArray) { string message; if(parameterArray.Length == 0) { message = format; } else { message = string.Format(format, parameterArray); } Console.WriteLine(string.Format("[{0}] {1}", DateTime.Now.ToString("HH:mm:ss"), message)); } #endregion } } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System; using System.ServiceModel; namespace TestServer { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { using(ServiceHost serviceHost = new ServiceHost(typeof(DataService))) { serviceHost.Open(); Console.WriteLine("서버가 시작되었습니다 : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); Console.ReadKey(true); } } #endregion } } |
▶ App.config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="mexBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <bindings> <basicHttpBinding> <binding name="basicHttp" sendTimeout="00:10:00" receiveTimeout="00:10:00" maxReceivedMessageSize="1262485504" transferMode="Streamed" /> </basicHttpBinding> <netTcpBinding> <binding name="netTcp" sendTimeout="00:10:00" receiveTimeout="00:10:00" maxReceivedMessageSize="1262485504" transferMode="Streamed" /> </netTcpBinding> </bindings> <services> <service name="TestServer.DataService" behaviorConfiguration="mexBehavior"> <endpoint address="DataService" binding="basicHttpBinding" bindingConfiguration="basicHttp" contract="TestServer.IDataService" /> <endpoint address="DataService" binding="netTcpBinding" bindingConfiguration="netTcp" contract="TestServer.IDataService" /> <host> <baseAddresses> <add baseAddress="http://localhost:8080" /> <add baseAddress="net.tcp://localhost:8090" /> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration> |
■ JsonSerializer 클래스를 사용해 스트림을 직렬화/역직렬화하는 방법을 보여준다. ▶ JSONHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
using System.IO; using Newtonsoft.Json; namespace TestProject { /// <summary> /// JSON 헬퍼 /// </summary> public static class JSONHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 포매팅 /// </summary> private static Formatting _formatting = Formatting.None; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region JSON 구하기 - GetJSON(sourceObject) /// <summary> /// JSON 구하기 /// </summary> /// <param name="sourceObject">소스 객체</param> /// <returns>JSON 문자열</returns> public static string GetJSON(object sourceObject) { string json = JsonConvert.SerializeObject(sourceObject, _formatting); return json; } #endregion #region 객체 구하기 - GetObject<T>(json) /// <summary> /// 객체 구하기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="json">JSON 문자열</param> /// <returns>객체</returns> public static T GetObject<T>(string json) { T targetObject = JsonConvert.DeserializeObject<T>(json); return targetObject; } #endregion #region 직렬화 하기 - Serialize(sourceObject, targetStream) /// <summary> /// 직렬화 하기 /// </summary> /// <param name="sourceObject">소스 객체</param> /// <param name="targetStream">타겟 스트림</param> public static void Serialize(object sourceObject, Stream targetStream) { using(StreamWriter streamWriter = new StreamWriter(targetStream)) { using(JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter)) { JsonSerializer jsonSerializer = new JsonSerializer(); jsonSerializer.Formatting = _formatting; jsonSerializer.Serialize(jsonTextWriter, sourceObject); jsonTextWriter.Flush(); } } } #endregion #region 역직렬화 하기 - Deserialize<T>(sourceStream) /// <summary> /// 역직렬화 하기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="sourceStream">소스 스트림</param> /// <returns>역직렬화 하기</returns> public static T Deserialize<T>(Stream sourceStream) { using(StreamReader streamReader = new StreamReader(sourceStream)) { using(JsonTextReader jsonTextReader = new JsonTextReader(streamReader)) { JsonSerializer jsonSerializer = new JsonSerializer(); jsonSerializer.Formatting = _formatting; T targetObject = jsonSerializer.Deserialize<T>(jsonTextReader); return targetObject; } } } #endregion } } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
using System; using System.Collections.Generic; using System.IO; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { /// <summary> /// 프로그램 시작하기 /// </summary> static void Main() { // 소스 리스트를 생성한다. List<TestData> sourceList = new List<TestData>(); for(int i = 0; i < 1000; i++) { sourceList.Add(new TestData { ID = i + 1, Name = "항목 " + (i + 1).ToString(), Grade = i % 5 + 1}); } // 파일 스트림에 직렬화 한다. FileStream targetFileStream = new FileStream("d:\\result.json", FileMode.CreateNew); JSONHelper.Serialize(sourceList, targetFileStream); // 파일 스트림에서 역직렬화 한다. FileStream sourceFileStream = new FileStream("d:\\a.json", FileMode.Open); List<TestData> targetList = JSONHelper.Deserialize<List<TestData>>(sourceFileStream); // 결과를 출력한다. Console.WriteLine("소스 리스트 : {0}건", sourceList.Count); Console.WriteLine("타겟 리스트 : {0}건", targetList.Count); } } } |
TestProject.zip
■ JsonConverter 클래스를 사용해 MemoryStream을 직렬화/역직렬화하는 방법을 보여준다. ▶ MemoryStreamJSONConverter.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
using System; using System.IO; using Newtonsoft.Json; namespace TestJSONStream { /// <summary> /// 메모리 스트림 JSON 컨버터 /// </summary> public class MemoryStreamJSONConverter : JsonConverter { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 변환 가능 여부 구하기 - CanConvert(objectType) /// <summary> /// 변환 가능 여부 구하기 /// </summary> /// <param name="objectType">객체 타입</param> /// <returns>변환 가능 여부</returns> public override bool CanConvert(Type objectType) { return typeof(MemoryStream).IsAssignableFrom(objectType); } #endregion #region JSON 읽기 - ReadJson(jsonReader, objectType, existingValue, jsonSerializer) /// <summary> /// JSON 읽기 /// </summary> /// <param name="jsonReader">JSON 리더</param> /// <param name="objectType">객체 타입</param> /// <param name="existingValue">기존 값</param> /// <param name="jsonSerializer">JSON 직렬화기</param> /// <returns>객체</returns> public override object ReadJson(JsonReader jsonReader, Type objectType, object existingValue, JsonSerializer jsonSerializer) { byte[] byteArray = jsonSerializer.Deserialize<byte[]>(jsonReader); return byteArray != null ? new MemoryStream(byteArray) : new MemoryStream(); } #endregion #region JSON 쓰기 - WriteJson(jsonWriter, value, jsonSerializer) /// <summary> /// JSON 쓰기 /// </summary> /// <param name="jsonWriter">JSON 라이터</param> /// <param name="value">값</param> /// <param name="jsonSerializer">JSON 직렬화기</param> public override void WriteJson(JsonWriter jsonWriter, object value, JsonSerializer jsonSerializer) { byte[] byteArray = ((MemoryStream)value).ToArray(); jsonSerializer.Serialize(jsonWriter, byteArray); } #endregion } } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
using System; using System.IO; using Newtonsoft.Json; namespace TestJSONStream { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { Console.Title = "JsonConverter 클래스 : MemoryStream 직렬화/역직렬화하기"; string source = "Test string"; Console.WriteLine("소스 문자열 : {0}", source); string json = GetJSON(source); Console.WriteLine("JSON 문자열 : {0}", json); string target = GetString(json); Console.WriteLine("타겟 문자열 : {0}", target); Console.Read(); } #endregion #region JSON 구하기 - GetJSON(source) /// <summary> /// JSON 구하기 /// </summary> /// <param name="source">소스 문자열</param> /// <returns>JSON 문자열</returns> public static string GetJSON(string source) { MemoryStream memoryStream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(memoryStream); streamWriter.WriteLine(source); streamWriter.Flush(); memoryStream.Position = 0; string json = JsonConvert.SerializeObject(memoryStream, Formatting.None, new MemoryStreamJSONConverter()); return json; } #endregion #region 문자열 구하기 - GetString(json) /// <summary> /// 문자열 구하기 /// </summary> /// <param name="json">JSON 문자열</param> /// <returns>문자열</returns> public static string GetString(string json) { MemoryStream memoryStream = JsonConvert.DeserializeObject<MemoryStream>(json, new MemoryStreamJSONConverter()); StreamReader streamReader = new StreamReader(memoryStream); string target = streamReader.ReadLine(); return target; } #endregion } } |
TestProject.zip
■ JObject 클래스를 사용해 JSON 문자열을 구하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System.IO; using Newtonsoft.Json.Linq; JObject jObject = new JObject ( new JProperty("Halo" , 9 ), new JProperty("Starcraft" , 9 ), new JProperty("Call of Duty", 7.5) ); File.WriteAllText(@"d:\sample.json", jObject.ToString()); |
▶ sample.json
1 2 3 4 5 6 7 |
{ "Halo": 9, "Starcraft": 9, "Call of Duty": 7.5 } |
※ Visual Studio NuGet 패키지
■ JavaScriptSerializer 클래스의 Serialize 메소드를 사용해 JSON을 직렬화하는 방법을 보여준다. ▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; using System.Web.Script.Serialization ; /// <summary> /// 학생 /// </summary> public class Student { /// <summary> /// ID /// </summary> public string ID; /// <summary> /// 성명 /// </summary> public string Name; /// <summary> /// 학년 /// </summary> public int Grade; } ... Student student = new Student() { ID = "A", Name = "홍길동", Grade = 3 }; JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string json = javaScriptSerializer.Serialize(student); Console.WriteLine(json); |
※ System.Web.Extensions 어셈블리 참조를 설정한다.