■ 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 } } |
▶ CSharpCodeWriter.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 |
using System; using System.IO; namespace TestLibrary { /// <summary> /// C# 코드 작성자 /// </summary> public class CSharpCodeWriter : ICodeWriter { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// NO RENAME ATTRIBUTE /// </summary> private const string NO_RENAME_ATTRIBUTE = "[Obfuscation(Feature = \"renaming\", Exclude = true)]"; /// <summary> /// NO PRUNE ATTRIBUTE /// </summary> private const string NO_PRUNE_ATTRIBUTE = "[Obfuscation(Feature = \"trigger\", Exclude = false)]"; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region (ICodeWriter) 파일 확장자 - FileExtension /// <summary> /// 파일 확장자 /// </summary> public string FileExtension { get { return ".cs"; } } #endregion #region (ICodeWriter) 디스플레이명 - DisplayName /// <summary> /// 디스플레이명 /// </summary> public string DisplayName { get { return "C#"; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region (ICodeWriter) 타입명 구하기 - GetTypeName(type, generator) /// <summary> /// 타입명 구하기 /// </summary> /// <param name="type">타입</param> /// <param name="generator">제너레이터</param> /// <returns>타입명</returns> public string GetTypeName(JSONType type, IJSONClassGenerator generator) { bool arraysAsLists = !generator.ExplicitDeserialization; switch(type.ValueType) { case JSONValueType.Anything : return "object"; case JSONValueType.Array : return arraysAsLists ? "IList<" + GetTypeName(type.InternalType, generator) + ">" : GetTypeName(type.InternalType, generator) + "[]"; case JSONValueType.Dictionary : return "Dictionary<string, " + GetTypeName(type.InternalType, generator) + ">"; case JSONValueType.Boolean : return "bool"; case JSONValueType.Float : return "double"; case JSONValueType.Integer : return "int"; case JSONValueType.Long : return "long"; case JSONValueType.Date : return "DateTime"; case JSONValueType.NonConstrained : return "object"; case JSONValueType.NullableBoolean : return "bool?"; case JSONValueType.NullableFloat : return "double?"; case JSONValueType.NullableInteger : return "int?"; case JSONValueType.NullableLong : return "long?"; case JSONValueType.NullableDate : return "DateTime?"; case JSONValueType.NullableSomething : return "object"; case JSONValueType.Object : return type.AssignedName; case JSONValueType.String : return "string"; default : throw new NotSupportedException("Unsupported json type"); } } #endregion #region (ICodeWriter) 클래스 쓰기 - WriteClass(generator, writer, type) /// <summary> /// 클래스 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="type">타입</param> public void WriteClass(IJSONClassGenerator generator, TextWriter writer, JSONType type) { string visibility = generator.InternalVisibility ? "internal" : "public"; if(generator.UseNestedClasses) { if(!type.IsRoot) { if(ShouldApplyNoRenamingAttribute(generator)) { writer.WriteLine(" " + NO_RENAME_ATTRIBUTE); } if(ShouldApplyNoPruneAttribute(generator)) { writer.WriteLine(" " + NO_PRUNE_ATTRIBUTE); } writer.WriteLine(" {0} class {1}", visibility, type.AssignedName); writer.WriteLine(" {"); } } else { if(ShouldApplyNoRenamingAttribute(generator)) { writer.WriteLine(" " + NO_RENAME_ATTRIBUTE); } if(ShouldApplyNoPruneAttribute(generator)) { writer.WriteLine(" " + NO_PRUNE_ATTRIBUTE); } writer.WriteLine(" {0} class {1}", visibility, type.AssignedName); writer.WriteLine(" {"); } string prefix = generator.UseNestedClasses && !type.IsRoot ? " " : " "; bool shouldSuppressWarning = generator.InternalVisibility && !generator.UseProperties && !generator.ExplicitDeserialization; if(shouldSuppressWarning) { writer.WriteLine("#pragma warning disable 0649"); if(!generator.UsePascalCase) { writer.WriteLine(); } } if(type.IsRoot && generator.ExplicitDeserialization) { WriteStringWithConstructorExplicitDeserialization(generator, writer, type, prefix); } if(generator.ExplicitDeserialization) { if(generator.UseProperties) { WriteClassWithPropertiesExplicitDeserialization(writer, type, prefix); } else { WriteClassWithFieldsExplicitDeserialization(writer, type, prefix); } } else { WriteClassMembers(generator, writer, type, prefix); } if(shouldSuppressWarning) { writer.WriteLine(); writer.WriteLine("#pragma warning restore 0649"); writer.WriteLine(); } if(generator.UseNestedClasses && !type.IsRoot) { writer.WriteLine(" }"); } if(!generator.UseNestedClasses) { writer.WriteLine(" }"); } writer.WriteLine(); } #endregion #region (ICodeWriter) 파일 시작 쓰기 - WriteFileStart(generator, writer) /// <summary> /// 파일 시작 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> public void WriteFileStart(IJSONClassGenerator generator, TextWriter writer) { if(generator.UseNamespaces) { foreach(string line in JSONClassGenerator.FileHeaderArray) { writer.WriteLine("// " + line); } writer.WriteLine(); writer.WriteLine("using System;"); writer.WriteLine("using System.Collections.Generic;"); if(ShouldApplyNoPruneAttribute(generator) || ShouldApplyNoRenamingAttribute(generator)) { writer.WriteLine("using System.Reflection;"); } if(!generator.ExplicitDeserialization && generator.UsePascalCase) { writer.WriteLine("using Newtonsoft.Json;"); } writer.WriteLine("using Newtonsoft.Json.Linq;"); if(generator.ExplicitDeserialization) { writer.WriteLine("using TestLibrary;"); } if(generator.SecondaryNamespace != null && generator.HasSecondaryClasses && !generator.UseNestedClasses) { writer.WriteLine("using {0};", generator.SecondaryNamespace); } } if(generator.UseNestedClasses) { writer.WriteLine(" {0} class {1}", generator.InternalVisibility ? "internal" : "public", generator.MainClass); writer.WriteLine(" {"); } } #endregion #region (ICodeWriter) 파일 종료 쓰기 - WriteFileEnd(generator, writer) /// <summary> /// 파일 종료 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> public void WriteFileEnd(IJSONClassGenerator generator, TextWriter writer) { if(generator.UseNestedClasses) { writer.WriteLine(" }"); } } #endregion #region (ICodeWriter) 네임스페이스 시작 쓰기 - WriteNamespaceStart(generator, writer, root) /// <summary> /// 네임스페이스 시작 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="root">루트 여부</param> public void WriteNamespaceStart(IJSONClassGenerator generator, TextWriter writer, bool root) { writer.WriteLine(); writer.WriteLine("namespace {0}", root && !generator.UseNestedClasses ? generator.Namespace : (generator.SecondaryNamespace ?? generator.Namespace)); writer.WriteLine("{"); writer.WriteLine(); } #endregion #region (ICodeWriter) 네임스페이스 종료 쓰기 - WriteNamespaceEnd(generator, writer, root) /// <summary> /// 네임스페이스 종료 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="root">루트 여부</param> public void WriteNamespaceEnd(IJSONClassGenerator generator, TextWriter writer, bool root) { writer.WriteLine("}"); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 이름 변경 어트리뷰트 미적용 의무 여부 구하기 - ShouldApplyNoRenamingAttribute(generator) /// <summary> /// 이름 변경 어트리뷰트 미적용 의무 여부 구하기 /// </summary> /// <param name="generator">제너레이터</param> /// <returns>이름 변경 어트리뷰트 미적용 의무 여부</returns> private bool ShouldApplyNoRenamingAttribute(IJSONClassGenerator generator) { return generator.ApplyObfuscationAttributes && !generator.ExplicitDeserialization && !generator.UsePascalCase; } #endregion #region 정리 어트리뷰트 미적용 여부 구하기 - ShouldApplyNoPruneAttribute(generator) /// <summary> /// 정리 어트리뷰트 미적용 여부 구하기 /// </summary> /// <param name="generator">제너레이터</param> /// <returns>정리 어트리뷰트 미적용 여부</returns> private bool ShouldApplyNoPruneAttribute(IJSONClassGenerator generator) { return generator.ApplyObfuscationAttributes && !generator.ExplicitDeserialization && generator.UseProperties; } #endregion #region 클래스 멤버 쓰기 - WriteClassMembers(generator, writer, type, prefix) /// <summary> /// 클래스 멤버 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="type">타입</param> /// <param name="prefix">접두사</param> private void WriteClassMembers(IJSONClassGenerator generator, TextWriter writer, JSONType type, string prefix) { foreach(FieldInfo fieldInfo in type.FieldInfoList) { if(generator.UsePascalCase || generator.ExamplesInDocumentation) { writer.WriteLine(); } if(generator.ExamplesInDocumentation) { writer.WriteLine(prefix + "/// <summary>"); writer.WriteLine(prefix + "/// Examples: " + fieldInfo.GetExampleText()); writer.WriteLine(prefix + "/// </summary>"); } if(generator.UsePascalCase) { writer.WriteLine(prefix + "[JsonProperty(\"{0}\")]", fieldInfo.JSONMemberName); } if(generator.UseProperties) { writer.WriteLine(prefix + "public {0} {1} {{ get; set; }}", fieldInfo.Type.GetTypeName(), fieldInfo.MemberName); } else { writer.WriteLine(prefix + "public {0} {1};", fieldInfo.Type.GetTypeName(), fieldInfo.MemberName); } } } #endregion #region 명시적 역직렬화 속성를 갖는 클래스 쓰기 - WriteClassWithPropertiesExplicitDeserialization(writer, type, prefix) /// <summary> /// 명시적 역직렬화 속성를 갖는 클래스 쓰기 /// </summary> /// <param name="writer">작성자</param> /// <param name="type">타입</param> /// <param name="prefix">접두사</param> private void WriteClassWithPropertiesExplicitDeserialization(TextWriter writer, JSONType type, string prefix) { writer.WriteLine(prefix + "private JObject __jobject;"); writer.WriteLine(prefix + "public {0}(JObject obj)", type.AssignedName); writer.WriteLine(prefix + "{"); writer.WriteLine(prefix + " this.__jobject = obj;"); writer.WriteLine(prefix + "}"); writer.WriteLine(); foreach(FieldInfo fieldInfo in type.FieldInfoList) { string variable = null; if(fieldInfo.Type.MustCache) { variable = "_" + char.ToLower(fieldInfo.MemberName[0]) + fieldInfo.MemberName.Substring(1); writer.WriteLine(prefix + "[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]"); writer.WriteLine(prefix + "private {0} {1};", fieldInfo.Type.GetTypeName(), variable); } writer.WriteLine(prefix + "public {0} {1}", fieldInfo.Type.GetTypeName(), fieldInfo.MemberName); writer.WriteLine(prefix + "{"); writer.WriteLine(prefix + " get"); writer.WriteLine(prefix + " {"); if(fieldInfo.Type.MustCache) { writer.WriteLine(prefix + " if ({0} == null)", variable); writer.WriteLine(prefix + " {0} = {1};", variable, fieldInfo.GetGenerationCode("__jobject")); writer.WriteLine(prefix + " return {0};", variable); } else { writer.WriteLine(prefix + " return {0};", fieldInfo.GetGenerationCode("__jobject")); } writer.WriteLine(prefix + " }"); writer.WriteLine(prefix + "}"); writer.WriteLine(); } } #endregion #region 명시적 역직렬화 생성자를 갖는 문자열 쓰기 - WriteStringWithConstructorExplicitDeserialization(generator, writer, type, prefix) /// <summary> /// 명시적 역직렬화 생성자를 갖는 문자열 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="type">타입</param> /// <param name="prefix">접두사</param> private void WriteStringWithConstructorExplicitDeserialization(IJSONClassGenerator generator, TextWriter writer, JSONType type, string prefix) { writer.WriteLine(); writer.WriteLine(prefix + "public {1}(string json)", generator.InternalVisibility ? "internal" : "public", type.AssignedName); writer.WriteLine(prefix + " : this(JObject.Parse(json))"); writer.WriteLine(prefix + "{"); writer.WriteLine(prefix + "}"); writer.WriteLine(); } #endregion #region 명시적 역직렬화 필드를 갖는 클래스 쓰기 - WriteClassWithFieldsExplicitDeserialization(writer, type, prefix) /// <summary> /// 명시적 역직렬화 필드를 갖는 클래스 쓰기 /// </summary> /// <param name="writer">작성자</param> /// <param name="type">타입</param> /// <param name="prefix">접두사</param> private void WriteClassWithFieldsExplicitDeserialization(TextWriter writer, JSONType type, string prefix) { writer.WriteLine(prefix + "public {0}(JObject obj)", type.AssignedName); writer.WriteLine(prefix + "{"); foreach(FieldInfo fieldInfo in type.FieldInfoList) { writer.WriteLine(prefix + " this.{0} = {1};", fieldInfo.MemberName, fieldInfo.GetGenerationCode("obj")); } writer.WriteLine(prefix + "}"); writer.WriteLine(); foreach(FieldInfo fieldInfo in type.FieldInfoList) { writer.WriteLine(prefix + "public readonly {0} {1};", fieldInfo.Type.GetTypeName(), fieldInfo.MemberName); } } #endregion } } |
▶ VisualBasicCodeWriter.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 |
using System; using System.IO; namespace TestLibrary { /// <summary> /// 비주얼 베이직 코드 작성자 /// </summary> public class VisualBasicCodeWriter : ICodeWriter { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// NO RENAME ATTRIBUTE /// </summary> private const string NO_RENAME_ATTRIBUTE = "<Obfuscation(Feature:=\"renaming\", Exclude:=true)>"; /// <summary> /// NO PRUNE ATTRIBUTE /// </summary> private const string NO_PRUNE_ATTRIBUTE = "<Obfuscation(Feature:=\"trigger\", Exclude:=false)>"; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region (ICodeWriter) 파일 확장자 - FileExtension /// <summary> /// 파일 확장자 /// </summary> public string FileExtension { get { return ".vb"; } } #endregion #region (ICodeWriter) 디스플레이명 - DisplayName /// <summary> /// 디스플레이명 /// </summary> public string DisplayName { get { return "Visual Basic .NET"; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region (ICodeWriter) 타입명 구하기 - GetTypeName(type, generator) /// <summary> /// 타입명 구하기 /// </summary> /// <param name="type">타입</param> /// <param name="generator">제너레이터</param> /// <returns>타입명</returns> public string GetTypeName(JSONType type, IJSONClassGenerator generator) { bool arraysAsLists = generator.ExplicitDeserialization; switch(type.ValueType) { case JSONValueType.Anything : return "Object"; case JSONValueType.Array : return arraysAsLists ? "IList(Of " + GetTypeName(type.InternalType, generator) + ")" : GetTypeName(type.InternalType, generator) + "()"; case JSONValueType.Dictionary : return "Dictionary(Of String, " + GetTypeName(type.InternalType, generator) + ")"; case JSONValueType.Boolean : return "Boolean"; case JSONValueType.Float : return "Double"; case JSONValueType.Integer : return "Integer"; case JSONValueType.Long : return "Long"; case JSONValueType.Date : return "DateTime"; case JSONValueType.NonConstrained : return "Object"; case JSONValueType.NullableBoolean : return "Boolean?"; case JSONValueType.NullableFloat : return "Double?"; case JSONValueType.NullableInteger : return "Integer?"; case JSONValueType.NullableLong : return "Long?"; case JSONValueType.NullableDate : return "DateTime?"; case JSONValueType.NullableSomething : return "Object"; case JSONValueType.Object : return type.AssignedName; case JSONValueType.String : return "String"; default : throw new NotSupportedException("Unsupported json type"); } } #endregion #region (ICodeWriter) 클래스 쓰기 - WriteClass(generator, writer, type) /// <summary> /// 클래스 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="type">타입</param> public void WriteClass(IJSONClassGenerator generator, TextWriter writer, JSONType type) { string visibility = generator.InternalVisibility ? "Friend" : "Public"; if(generator.UseNestedClasses) { writer.WriteLine(" {0} Partial Class {1}", visibility, generator.MainClass); if(!type.IsRoot) { if(ShouldApplyNoRenamingAttribute(generator)) { writer.WriteLine(" " + NO_RENAME_ATTRIBUTE); } if(ShouldApplyNoPruneAttribute(generator)) { writer.WriteLine(" " + NO_PRUNE_ATTRIBUTE); } writer.WriteLine(" {0} Class {1}", visibility, type.AssignedName); } } else { if(ShouldApplyNoRenamingAttribute(generator)) { writer.WriteLine(" " + NO_RENAME_ATTRIBUTE); } if(ShouldApplyNoPruneAttribute(generator)) { writer.WriteLine(" " + NO_PRUNE_ATTRIBUTE); } writer.WriteLine(" {0} Class {1}", visibility, type.AssignedName); } string prefix = generator.UseNestedClasses && !type.IsRoot ? " " : " "; WriteClassMembers(generator, writer, type, prefix); if(generator.UseNestedClasses && !type.IsRoot) { writer.WriteLine(" End Class"); } writer.WriteLine(" End Class"); writer.WriteLine(); } #endregion #region (ICodeWriter) 파일 시작 쓰기 - WriteFileStart(generator, writer) /// <summary> /// 파일 시작 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> public void WriteFileStart(IJSONClassGenerator generator, TextWriter writer) { foreach(string line in JSONClassGenerator.FileHeaderArray) { writer.WriteLine("' " + line); } writer.WriteLine(); writer.WriteLine("Imports System"); writer.WriteLine("Imports System.Collections.Generic"); if(ShouldApplyNoRenamingAttribute(generator) || ShouldApplyNoPruneAttribute(generator)) { writer.WriteLine("Imports System.Reflection"); } if(generator.UsePascalCase) { writer.WriteLine("Imports Newtonsoft.Json"); } writer.WriteLine("Imports Newtonsoft.Json.Linq"); if(generator.SecondaryNamespace != null && generator.HasSecondaryClasses && !generator.UseNestedClasses) { writer.WriteLine("Imports {0}", generator.SecondaryNamespace); } } #endregion #region (ICodeWriter) 파일 종료 쓰기 - WriteFileEnd(generator, writer) /// <summary> /// 파일 종료 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> public void WriteFileEnd(IJSONClassGenerator generator, TextWriter writer) { } #endregion #region (ICodeWriter) 네임스페이스 시작 쓰기 - WriteNamespaceStart(generator, writer, root) /// <summary> /// 네임스페이스 시작 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="root">루트 여부</param> public void WriteNamespaceStart(IJSONClassGenerator generator, TextWriter writer, bool root) { writer.WriteLine(); writer.WriteLine("Namespace Global.{0}", root && !generator.UseNestedClasses ? generator.Namespace : (generator.SecondaryNamespace ?? generator.Namespace)); writer.WriteLine(); } #endregion #region (ICodeWriter) 네임스페이스 종료 쓰기 - WriteNamespaceEnd(generator, writer, root) /// <summary> /// 네임스페이스 종료 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="root">루트 여부</param> public void WriteNamespaceEnd(IJSONClassGenerator generator, TextWriter writer, bool root) { writer.WriteLine("End Namespace"); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 이름 변경 어트리뷰트 미적용 의무 여부 구하기 - ShouldApplyNoRenamingAttribute(generator) /// <summary> /// 이름 변경 어트리뷰트 미적용 의무 여부 구하기 /// </summary> /// <param name="generator">제너레이터</param> /// <returns>이름 변경 어트리뷰트 미적용 의무 여부</returns> private bool ShouldApplyNoRenamingAttribute(IJSONClassGenerator generator) { return generator.ApplyObfuscationAttributes && !generator.ExplicitDeserialization && !generator.UsePascalCase; } #endregion #region 정리 어트리뷰트 미적용 의무 여부 구하기 - ShouldApplyNoPruneAttribute(generator) /// <summary> /// 정리 어트리뷰트 미적용 의무 여부 구하기 /// </summary> /// <param name="generator">제너레이터</param> /// <returns>정리 어트리뷰트 미적용 의무 여부</returns> private bool ShouldApplyNoPruneAttribute(IJSONClassGenerator generator) { return generator.ApplyObfuscationAttributes && !generator.ExplicitDeserialization && generator.UseProperties; } #endregion #region 클래스 멤버 쓰기 - WriteClassMembers(generator, writer, type, prefix) /// <summary> /// 클래스 멤버 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="type">타입</param> /// <param name="prefix">접두사</param> private void WriteClassMembers(IJSONClassGenerator generator, TextWriter writer, JSONType type, string prefix) { foreach(FieldInfo fieldInfo in type.FieldInfoList) { if(generator.UsePascalCase || generator.ExamplesInDocumentation) { writer.WriteLine(); } if(generator.ExamplesInDocumentation) { writer.WriteLine(prefix + "''' <summary>"); writer.WriteLine(prefix + "''' Examples: " + fieldInfo.GetExampleText()); writer.WriteLine(prefix + "''' </summary>"); } if(generator.UsePascalCase) { writer.WriteLine(prefix + "<JsonProperty(\"{0}\")>", fieldInfo.JSONMemberName); } if(generator.UseProperties) { writer.WriteLine(prefix + "Public Property {1} As {0}", fieldInfo.Type.GetTypeName(), fieldInfo.MemberName); } else { writer.WriteLine(prefix + "Public {1} As {0}", fieldInfo.Type.GetTypeName(), fieldInfo.MemberName); } } } #endregion } } |
▶ TypeScriptCodeWriter.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 |
using System; using System.IO; namespace TestLibrary { /// <summary> /// 타입 스크립트 코드 작성자 /// </summary> public class TypeScriptCodeWriter : ICodeWriter { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region (ICodeWriter) 파일 확장자 - FileExtension /// <summary> /// 파일 확장자 /// </summary> public string FileExtension { get { return ".ts"; } } #endregion #region (ICodeWriter) 디스플레이명 - DisplayName /// <summary> /// 디스플레이명 /// </summary> public string DisplayName { get { return "TypeScript"; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region (ICodeWriter) 타입명 구하기 - GetTypeName(type, generator) /// <summary> /// 타입명 구하기 /// </summary> /// <param name="type">타입</param> /// <param name="generator">제너레이터</param> /// <returns>타입명</returns> public string GetTypeName(JSONType type, IJSONClassGenerator generator) { switch(type.ValueType) { case JSONValueType.Anything : return "any"; case JSONValueType.String : return "string"; case JSONValueType.Boolean : return "bool"; case JSONValueType.Integer : case JSONValueType.Long : case JSONValueType.Float : return "number"; case JSONValueType.Date : return "Date"; case JSONValueType.NullableInteger : case JSONValueType.NullableLong : case JSONValueType.NullableFloat : return "number"; case JSONValueType.NullableBoolean : return "bool"; case JSONValueType.NullableDate : return "Date"; case JSONValueType.Object : return type.AssignedName; case JSONValueType.Array : return GetTypeName(type.InternalType, generator) + "[]"; case JSONValueType.Dictionary : return "{ [key: string]: " + GetTypeName(type.InternalType, generator) + "; }"; case JSONValueType.NullableSomething : return "any"; case JSONValueType.NonConstrained : return "any"; default : throw new NotSupportedException("Unsupported type"); } } #endregion #region (ICodeWriter) 클래스 쓰기 - WriteClass(generator, writer, type) /// <summary> /// 클래스 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="type">타입</param> public void WriteClass(IJSONClassGenerator generator, TextWriter writer, JSONType type) { string prefix = GetNamespace(generator, type.IsRoot) != null ? " " : ""; bool exported = !generator.InternalVisibility || generator.SecondaryNamespace != null; writer.WriteLine(prefix + (exported ? "export " : string.Empty) + "interface " + type.AssignedName + " {"); foreach(FieldInfo fieldInfo in type.FieldInfoList) { bool shouldDefineNamespace = type.IsRoot && generator.SecondaryNamespace != null && generator.Namespace != null && ( fieldInfo.Type.ValueType == JSONValueType.Object || (fieldInfo.Type.InternalType != null && fieldInfo.Type.InternalType.ValueType == JSONValueType.Object) ); if(generator.ExamplesInDocumentation) { writer.WriteLine(); writer.WriteLine(prefix + " /**"); writer.WriteLine(prefix + " * Examples: " + fieldInfo.GetExampleText()); writer.WriteLine(prefix + " */"); } writer.WriteLine ( prefix + " " + fieldInfo.JSONMemberName + (IsNullable(fieldInfo.Type.ValueType) ? "?" : "") + ": " + (shouldDefineNamespace ? generator.SecondaryNamespace + "." : string.Empty) + GetTypeName(fieldInfo.Type, generator) + ";" ); } writer.WriteLine(prefix + "}"); writer.WriteLine(); } #endregion #region (ICodeWriter) 파일 시작 쓰기 - WriteFileStart(generator, writer) /// <summary> /// 파일 시작 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> public void WriteFileStart(IJSONClassGenerator generator, TextWriter writer) { foreach(string line in JSONClassGenerator.FileHeaderArray) { writer.WriteLine("// " + line); } writer.WriteLine(); } #endregion #region (ICodeWriter) 파일 종료 쓰기 - WriteFileEnd(generator, writer) /// <summary> /// 파일 종료 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> public void WriteFileEnd(IJSONClassGenerator generator, TextWriter writer) { } #endregion #region (ICodeWriter) 네임스페이스 시작 쓰기 - WriteNamespaceStart(generator, writer, root) /// <summary> /// 네임스페이스 시작 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="root">루트 여부</param> public void WriteNamespaceStart(IJSONClassGenerator generator, TextWriter writer, bool root) { if(GetNamespace(generator, root) != null) { writer.WriteLine("module " + GetNamespace(generator, root) + " {"); writer.WriteLine(); } } #endregion #region (ICodeWriter) 네임스페이스 종료 쓰기 - WriteNamespaceEnd(generator, writer, root) /// <summary> /// 네임스페이스 종료 쓰기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="writer">작성자</param> /// <param name="root">루트 여부</param> public void WriteNamespaceEnd(IJSONClassGenerator generator, TextWriter writer, bool root) { if(GetNamespace(generator, root) != null) { writer.WriteLine("}"); writer.WriteLine(); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region NULL 가능 여부 구하기 - IsNullable(valueType) /// <summary> /// NULL 가능 여부 구하기 /// </summary> /// <param name="valueType">값 타입</param> /// <returns>NULL 가능 여부</returns> private bool IsNullable(JSONValueType valueType) { return valueType == JSONValueType.NullableBoolean || valueType == JSONValueType.NullableDate || valueType == JSONValueType.NullableFloat || valueType == JSONValueType.NullableInteger || valueType == JSONValueType.NullableLong || valueType == JSONValueType.NullableSomething; } #endregion #region 네임스페이스 구하기 - GetNamespace(generator, root) /// <summary> /// 네임스페이스 구하기 /// </summary> /// <param name="generator">제너레이터</param> /// <param name="root">루트 여부</param> /// <returns>네임스페이스</returns> private string GetNamespace(IJSONClassGenerator generator, bool root) { return root ? generator.Namespace : (generator.SecondaryNamespace ?? generator.Namespace); } #endregion } } |
▶ JSONClassHelper.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 |
using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace TestLibrary { /// <summary> /// JSON 클래스 헬퍼 /// </summary> internal static class JSONClassHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Delegate ////////////////////////////////////////////////////////////////////////////////////////// Public #region 값 리더 대리자 - ValueReader<T>(token) /// <summary> /// 값 리더 대리자 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="token">토큰</param> /// <returns>값</returns> public delegate T ValueReader<T>(JToken token); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region JSON 토큰 구하기 - GetJToken<T>(jObject, field) /// <summary> /// JSON 토큰 구하기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="jObject">JSON 객체</param> /// <param name="field">필드</param> /// <returns>JSON 토큰</returns> public static T GetJToken<T>(JObject jObject, string field) where T : JToken { JToken token; if(jObject.TryGetValue(field, out token)) { return GetJToken<T>(token); } else { return null; } } #endregion #region 문자열 읽기 - ReadString(token) /// <summary> /// 문자열 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>문자열</returns> public static string ReadString(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { return null; } return (string)value.Value; } #endregion #region 진리값 읽기 - ReadBoolean(token) /// <summary> /// 진리값 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>진리값</returns> public static bool ReadBoolean(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { throw new JsonSerializationException(); } return Convert.ToBoolean(value.Value); } #endregion #region NULL 가능 진리값 읽기 - ReadNullableBoolean(token) /// <summary> /// NULL 가능 진리값 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>NULL 가능 진리값</returns> public static bool? ReadNullableBoolean(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { return null; } return Convert.ToBoolean(value.Value); } #endregion #region 정수 읽기 - ReadInteger(token) /// <summary> /// 정수 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>정수</returns> public static int ReadInteger(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { throw new JsonSerializationException(); } return Convert.ToInt32((long)value.Value); } #endregion #region NULL 가능 정수 읽기 - ReadNullableInteger(token) /// <summary> /// NULL 가능 정수 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>NULL 가능 정수</returns> public static int? ReadNullableInteger(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { return null; } return Convert.ToInt32((long)value.Value); } #endregion #region 배정도 정수 읽기 - ReadLong(token) /// <summary> /// 배정도 정수 읽기 /// </summary> /// <param name="token"></param> /// <returns>배정도 정수</returns> public static long ReadLong(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { throw new JsonSerializationException(); } return Convert.ToInt64(value.Value); } #endregion #region NULL 가능 배정도 정수 읽기 - ReadNullableLong(token) /// <summary> /// NULL 가능 배정도 정수 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>NULL 가능 배정도 정수</returns> public static long? ReadNullableLong(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { return null; } return Convert.ToInt64(value.Value); } #endregion #region 부동형 실수 읽기 - ReadFloat(token) /// <summary> /// 부동형 실수 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>부동형 실수</returns> public static double ReadFloat(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { throw new JsonSerializationException(); } return Convert.ToDouble(value.Value); } #endregion #region NULL 가능 부동형 실수 읽기 - ReadNullableFloat(token) /// <summary> /// NULL 가능 부동형 실수 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>NULL 가능 부동형 실수</returns> public static double? ReadNullableFloat(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { return null; } return Convert.ToDouble(value.Value); } #endregion #region 날짜 읽기 - ReadDate(token) /// <summary> /// 날짜 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>날짜</returns> public static DateTime ReadDate(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { throw new JsonSerializationException(); } return Convert.ToDateTime(value.Value); } #endregion #region NULL 가능 날짜 읽기 - ReadNullableDate(token) /// <summary> /// NULL 가능 날짜 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>NULL 가능 날짜</returns> public static DateTime? ReadNullableDate(JToken token) { JValue value = GetJToken<JValue>(token); if(value == null) { return null; } return Convert.ToDateTime(value.Value); } #endregion #region 객체 읽기 - ReadObject(token) /// <summary> /// 객체 읽기 /// </summary> /// <param name="token">토큰</param> /// <returns>객체</returns> public static object ReadObject(JToken token) { JToken value = GetJToken<JToken>(token); if(value == null) { return null; } if(value.Type == JTokenType.Object) { return value; } if(value.Type == JTokenType.Array) { return ReadArray<object>(value, ReadObject); } JValue jValue = value as JValue; if(jValue != null) { return jValue.Value; } return value; } #endregion #region 강력한 타입 객체 읽기 - ReadStronglyTypedObject<T>(token) /// <summary> /// 강력한 타입 객체 읽기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="token">토큰</param> /// <returns>강력한 타입 객체</returns> public static T ReadStronglyTypedObject<T>(JToken token) where T : class { JObject value = GetJToken<JObject>(token); if(value == null) { return null; } return (T)Activator.CreateInstance(typeof(T), new object[] { token }); } #endregion #region 배열 읽기 - ReadArray<T>(token, reader) /// <summary> /// 배열 읽기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="token">토큰</param> /// <param name="reader">리더</param> /// <returns>배열</returns> public static T[] ReadArray<T>(JToken token, ValueReader<T> reader) { JArray value = GetJToken<JArray>(token); if(value == null) { return null; } T[] array = new T[value.Count]; for(int i = 0; i < array.Length; i++) { array[i] = reader(value[i]); } return array; } #endregion #region 딕셔너리 읽기 - ReadDictionary<T>(token) /// <summary> /// 딕셔너리 읽기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="token">토큰</param> /// <returns>딕셔너리</returns> public static Dictionary<string, T> ReadDictionary<T>(JToken token) { JObject value = GetJToken<JObject>(token); if(value == null) { return null; } Dictionary<string, T> dictionary = new Dictionary<string, T>(); return dictionary; } #endregion #region 배열 읽기 - ReadArray<K>(jArray, reader, type) /// <summary> /// 배열 읽기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="jArray">JSON 배열</param> /// <param name="reader">리더</param> /// <param name="type">타입</param> /// <returns>배열</returns> public static Array ReadArray<T>(JArray jArray, ValueReader<T> reader, Type type) { if(jArray == null) { return null; } Type elementType = type.GetElementType(); Array array = Array.CreateInstance(elementType, jArray.Count); for(int i = 0; i < array.Length; i++) { if(elementType.IsArray) { array.SetValue(ReadArray<T>(GetJToken<JArray>(jArray[i]), reader, elementType), i); } else { array.SetValue(reader(jArray[i]), i); } } return array; } #endregion //////////////////////////////////////////////////////////////////////////////// Private #region JSON 토큰 구하기 - GetJToken<T>(token) /// <summary> /// JSON 토큰 구하기 /// </summary> /// <typeparam name="T">타입</typeparam> /// <param name="token">토큰</param> /// <returns>JSON 토큰</returns> private static T GetJToken<T>(JToken token) where T : JToken { if(token == null) { return null; } if(token.Type == JTokenType.Null) { return null; } if(token.Type == JTokenType.Undefined) { return null; } return (T)token; } #endregion } } |
▶ IJSONClassGenerator.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 |
namespace TestLibrary { /// <summary> /// JSON 클래스 제너레이터 인터페이스 /// </summary> public interface IJSONClassGenerator { //////////////////////////////////////////////////////////////////////////////////////////////////// Property #region 네임스페이스 - Namespace /// <summary> /// 네임스페이스 /// </summary> string Namespace { get; set; } #endregion #region 보조 네임스페이스 - SecondaryNamespace /// <summary> /// 보조 네임스페이스 /// </summary> string SecondaryNamespace { get; set; } #endregion #region 속성 사용 여부 - UseProperties /// <summary> /// 속성 사용 여부 /// </summary> bool UseProperties { get; set; } #endregion #region 내부 표시 여부 - InternalVisibility /// <summary> /// 내부 표시 여부 /// </summary> bool InternalVisibility { get; set; } #endregion #region 명시적 역직렬화 - ExplicitDeserialization /// <summary> /// 명시적 역직렬화 /// </summary> bool ExplicitDeserialization { get; set; } #endregion #region 헬퍼 클래스 없음 여부 - NoHelperClass /// <summary> /// 헬퍼 클래스 없음 여부 /// </summary> bool NoHelperClass { get; set; } #endregion #region 메인 클래스 - MainClass /// <summary> /// 메인 클래스 /// </summary> string MainClass { get; set; } #endregion #region 파스칼 표기법 사용 여부 - UsePascalCase /// <summary> /// 파스칼 표기법 사용 여부 /// </summary> bool UsePascalCase { get; set; } #endregion #region 중첩 클래스 사용 여부 - UseNestedClasses /// <summary> /// 중첩 클래스 사용 여부 /// </summary> bool UseNestedClasses { get; set; } #endregion #region 난독화 어트리뷰트 적용 여부 - ApplyObfuscationAttributes /// <summary> /// 난독화 어트리뷰트 적용 여부 /// </summary> bool ApplyObfuscationAttributes { get; set; } #endregion #region 단일 파일 여부 - SingleFile /// <summary> /// 단일 파일 여부 /// </summary> bool SingleFile { get; set; } #endregion #region 코드 작성자 - CodeWriter /// <summary> /// 코드 작성자 /// </summary> ICodeWriter CodeWriter { get; set; } #endregion #region 보조 클래스 보유 여부 - HasSecondaryClasses /// <summary> /// 보조 클래스 보유 여부 /// </summary> bool HasSecondaryClasses { get; } #endregion #region NULL 가능 값 항상 사용 여부 - AlwaysUseNullableValues /// <summary> /// NULL 가능 값 항상 사용 여부 /// </summary> bool AlwaysUseNullableValues { get; set; } #endregion #region 네임스페이스 사용 여부 - UseNamespaces /// <summary> /// 네임스페이스 사용 여부 /// </summary> bool UseNamespaces { get; } #endregion #region 문서 내 예제 여부 - ExamplesInDocumentation /// <summary> /// 문서 내 예제 여부 /// </summary> bool ExamplesInDocumentation { get; set; } #endregion } } |
▶ JSONClassGenerator.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 |
using System; using System.Collections.Generic; using System.Data.Entity.Design.PluralizationServices; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace TestLibrary { /// <summary> /// JSON 클래스 제너레이터 /// </summary> public class JSONClassGenerator : IJSONClassGenerator { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 파일 헤더 배열 - FileHeaderArray /// <summary> /// 파일 헤더 배열 /// </summary> public static readonly string[] FileHeaderArray = new[] { "Generated by JSON Class Generator", "https://icodebroker.tistory.com" }; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 서비스 /// </summary> private PluralizationService service = PluralizationService.CreateService(new CultureInfo("en-us")); /// <summary> /// 사용 여부 /// </summary> private bool used = false; /// <summary> /// 명칭 해시 세트 /// </summary> private HashSet<string> nameHashSet = new HashSet<string>(); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region (IJSONClassGenerator) 네임스페이스 - Namespace /// <summary> /// 네임스페이스 /// </summary> public string Namespace { get; set; } #endregion #region (IJSONClassGenerator) 보조 네임스페이스 - SecondaryNamespace /// <summary> /// 보조 네임스페이스 /// </summary> public string SecondaryNamespace { get; set; } #endregion #region (IJSONClassGenerator) 속성 사용 여부 - UseProperties /// <summary> /// 속성 사용 여부 /// </summary> public bool UseProperties { get; set; } #endregion #region (IJSONClassGenerator) 내부 표시 여부 - InternalVisibility /// <summary> /// 내부 표시 여부 /// </summary> public bool InternalVisibility { get; set; } #endregion #region (IJSONClassGenerator) 명시적 역직렬화 - ExplicitDeserialization /// <summary> /// 명시적 역직렬화 /// </summary> public bool ExplicitDeserialization { get; set; } #endregion #region (IJSONClassGenerator) 헬퍼 클래스 없음 여부 - NoHelperClass /// <summary> /// 헬퍼 클래스 없음 여부 /// </summary> public bool NoHelperClass { get; set; } #endregion #region (IJSONClassGenerator) 메인 클래스 - MainClass /// <summary> /// 메인 클래스 /// </summary> public string MainClass { get; set; } #endregion #region (IJSONClassGenerator) 파스칼 표기법 사용 여부 - UsePascalCase /// <summary> /// 파스칼 표기법 사용 여부 /// </summary> public bool UsePascalCase { get; set; } #endregion #region (IJSONClassGenerator) 중첩 클래스 사용 여부 - UseNestedClasses /// <summary> /// 중첩 클래스 사용 여부 /// </summary> public bool UseNestedClasses { get; set; } #endregion #region (IJSONClassGenerator) 난독화 어트리뷰트 적용 여부 - ApplyObfuscationAttributes /// <summary> /// 난독화 어트리뷰트 적용 여부 /// </summary> public bool ApplyObfuscationAttributes { get; set; } #endregion #region (IJSONClassGenerator) 단일 파일 여부 - SingleFile /// <summary> /// 단일 파일 여부 /// </summary> public bool SingleFile { get; set; } #endregion #region (IJSONClassGenerator) 코드 작성자 - CodeWriter /// <summary> /// 코드 작성자 /// </summary> public ICodeWriter CodeWriter { get; set; } #endregion #region (IJSONClassGenerator) 보조 클래스 보유 여부 - HasSecondaryClasses /// <summary> /// 보조 클래스 보유 여부 /// </summary> public bool HasSecondaryClasses { get { return TypeList.Count > 1; } } #endregion #region (IJSONClassGenerator) NULL 가능 값 항상 사용 여부 - AlwaysUseNullableValues /// <summary> /// NULL 가능 값 항상 사용 여부 /// </summary> public bool AlwaysUseNullableValues { get; set; } #endregion #region (IJSONClassGenerator) 네임스페이스 사용 여부 - UseNamespaces /// <summary> /// 네임스페이스 사용 여부 /// </summary> public bool UseNamespaces { get { return Namespace != null; } } #endregion #region (IJSONClassGenerator) 문서 내 예제 여부 - ExamplesInDocumentation /// <summary> /// 문서 내 예제 여부 /// </summary> public bool ExamplesInDocumentation { get; set; } #endregion #region 예제 - Example /// <summary> /// 예제 /// </summary> public string Example { get; set; } #endregion #region 타겟 디렉토리 경로 - TargetDirectoryPath /// <summary> /// 타겟 디렉토리 경로 /// </summary> public string TargetDirectoryPath { get; set; } #endregion #region 작성자 - Writer /// <summary> /// 작성자 /// </summary> public TextWriter Writer { get; set; } #endregion #region 타입 리스트 - TypeList /// <summary> /// 타입 리스트 /// </summary> public IList<JSONType> TypeList { get; private set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 클래스 생성하기 - GenerateClasses() /// <summary> /// 클래스 생성하기 /// </summary> public void GenerateClasses() { if(CodeWriter == null) { CodeWriter = new CSharpCodeWriter(); } if(ExplicitDeserialization && !(CodeWriter is CSharpCodeWriter)) { throw new ArgumentException("Explicit deserialization is obsolete and is only supported by the C# provider."); } if(this.used) { throw new InvalidOperationException("This instance of JsonClassGenerator has already been used. Please create a new instance."); } this.used = true; bool writeToDisk = TargetDirectoryPath != null; if(writeToDisk && !Directory.Exists(TargetDirectoryPath)) { Directory.CreateDirectory(TargetDirectoryPath); } JObject[] exampleArray; string example = Example.StartsWith("HTTP/") ? Example.Substring(Example.IndexOf("\r\n\r\n")) : Example; using(StringReader stringReader = new StringReader(example)) { using(JsonTextReader jsonTextReader = new JsonTextReader(stringReader)) { JToken token = JToken.ReadFrom(jsonTextReader); if(token is JArray) { exampleArray = ((JArray)token).Cast<JObject>().ToArray(); } else if(token is JObject) { exampleArray = new[] { (JObject)token }; } else { throw new Exception("Sample JSON must be either a JSON array, or a JSON object."); } } } TypeList = new List<JSONType>(); this.nameHashSet.Add(MainClass); JSONType rootType = new JSONType(this, exampleArray[0]); rootType.IsRoot = true; rootType.AssignName(MainClass); GenerateClass(exampleArray, rootType); if(writeToDisk) { string parentFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); if(writeToDisk && !NoHelperClass && ExplicitDeserialization) { File.WriteAllBytes(Path.Combine(TargetDirectoryPath, "JSONClassHelper.cs"), Properties.Resources.JSONClassHelper); } if(SingleFile) { WriteClassesToFile(Path.Combine(TargetDirectoryPath, MainClass + CodeWriter.FileExtension), TypeList); } else { foreach(JSONType type in TypeList) { string directoryPath = TargetDirectoryPath; if(!UseNestedClasses && !type.IsRoot && SecondaryNamespace != null) { string temporaryNamespace = SecondaryNamespace; if(temporaryNamespace.StartsWith(Namespace + ".")) { temporaryNamespace = temporaryNamespace.Substring(Namespace.Length + 1); } directoryPath = Path.Combine(directoryPath, temporaryNamespace); Directory.CreateDirectory(directoryPath); } WriteClassesToFile ( Path.Combine(directoryPath, (UseNestedClasses && !type.IsRoot ? MainClass + "." : string.Empty) + type.AssignedName + CodeWriter.FileExtension), new[] { type } ); } } } else if(Writer != null) { WriteClassesToFile(Writer, TypeList); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Internal #region 제목 케이스 구하기 - ToTitleCase(source) /// <summary> /// 제목 케이스 구하기 /// </summary> /// <param name="source">소스 문자열</param> /// <returns>제목 케이스</returns> internal static string ToTitleCase(string source) { StringBuilder stringBuilder = new StringBuilder(source.Length); bool flag = true; for(int i = 0; i < source.Length; i++) { char character = source[i]; if(char.IsLetterOrDigit(character)) { stringBuilder.Append(flag ? char.ToUpper(character) : character); flag = false; } else { flag = true; } } return stringBuilder.ToString(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 유일한 클래스명 생성하기 - CreateUniqueClassName(name) /// <summary> /// 유일한 클래스명 생성하기 /// </summary> /// <param name="name">명칭</param> /// <returns>유일한 클래스명</returns> private string CreateUniqueClassName(string name) { name = ToTitleCase(name); string finalName = name; int i = 2; while(this.nameHashSet.Any(x => x.Equals(finalName, StringComparison.OrdinalIgnoreCase))) { finalName = name + i.ToString(); i++; } this.nameHashSet.Add(finalName); return finalName; } #endregion #region 복수의 값에서 유일한 클래스명 생성하기 - CreateUniqueClassNameFromPlural(plural) /// <summary> /// 복수의 문자열에서 유일한 클래스명 생성하기 /// </summary> /// <param name="plural">복수의 문자열</param> /// <returns>유일한 클래스명</returns> private string CreateUniqueClassNameFromPlural(string plural) { plural = ToTitleCase(plural); return CreateUniqueClassName(this.service.Singularize(plural)); } #endregion #region 클래스 생성하기 - GenerateClass(exampleArray, type) /// <summary> /// 클래스 생성하기 /// </summary> /// <param name="exampleArray">예제 배열</param> /// <param name="type">타입</param> private void GenerateClass(JObject[] exampleArray, JSONType type) { Dictionary<string, JSONType> jsonFieldDictionary = new Dictionary<string, JSONType>(); Dictionary<string, IList<object>> fieldExampleDictionary = new Dictionary<string, IList<object>>(); bool first = true; foreach(JObject jObject in exampleArray) { foreach(JProperty jProperty in jObject.Properties()) { JSONType fieldType; JSONType currentType = new JSONType(this, jProperty.Value); string propertyName = jProperty.Name; if(jsonFieldDictionary.TryGetValue(propertyName, out fieldType)) { JSONType commonType = fieldType.GetCommonType(currentType); jsonFieldDictionary[propertyName] = commonType; } else { JSONType commonType = currentType; if(first) { commonType = commonType.MaybeMakeNullable(this); } else { commonType = commonType.GetCommonType(JSONType.GetNull(this)); } jsonFieldDictionary.Add(propertyName, commonType); fieldExampleDictionary[propertyName] = new List<object>(); } IList<object> fieldExample = fieldExampleDictionary[propertyName]; JToken token = jProperty.Value; if(token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) { if(!fieldExample.Contains(null)) { fieldExample.Insert(0, null); } } else { object value = token.Type == JTokenType.Array || token.Type == JTokenType.Object ? token : token.Value<object>(); if(!fieldExample.Any(x => value.Equals(x))) { fieldExample.Add(value); } } } first = false; } if(UseNestedClasses) { foreach(KeyValuePair<string, JSONType> keyValuePair in jsonFieldDictionary) { this.nameHashSet.Add(keyValuePair.Key.ToLower()); } } foreach(KeyValuePair<string, JSONType> keyValuePair in jsonFieldDictionary) { JSONType fieldType = keyValuePair.Value; if(fieldType.ValueType == JSONValueType.Object) { List<JObject> subsidaryExampleList = new List<JObject>(exampleArray.Length); foreach(JObject jObject in exampleArray) { JToken value; if(jObject.TryGetValue(keyValuePair.Key, out value)) { if(value.Type == JTokenType.Object) { subsidaryExampleList.Add((JObject)value); } } } fieldType.AssignName(CreateUniqueClassName(keyValuePair.Key)); GenerateClass(subsidaryExampleList.ToArray(), fieldType); } if(fieldType.InternalType != null && fieldType.InternalType.ValueType == JSONValueType.Object) { List<JObject> subsidaryExampleList = new List<JObject>(exampleArray.Length); foreach(JObject jObject in exampleArray) { JToken value; if(jObject.TryGetValue(keyValuePair.Key, out value)) { if(value.Type == JTokenType.Array) { foreach(JToken item in (JArray)value) { if(!(item is JObject)) { throw new NotSupportedException("Arrays of non-objects are not supported yet."); } subsidaryExampleList.Add((JObject)item); } } else if(value.Type == JTokenType.Object) { foreach(KeyValuePair<string, JToken> item in (JObject)value) { if(!(item.Value is JObject)) { throw new NotSupportedException("Arrays of non-objects are not supported yet."); } subsidaryExampleList.Add((JObject)item.Value); } } } } keyValuePair.Value.InternalType.AssignName(CreateUniqueClassNameFromPlural(keyValuePair.Key)); GenerateClass(subsidaryExampleList.ToArray(), keyValuePair.Value.InternalType); } } type.FieldInfoList = jsonFieldDictionary.Select(x => new FieldInfo(this, x.Key, x.Value, UsePascalCase, fieldExampleDictionary[x.Key])).ToArray(); TypeList.Add(type); } #endregion #region 파일에 클래스 쓰기 - WriteClassesToFile(writer, typeEnumerable) /// <summary> /// 파일에 클래스 쓰기 /// </summary> /// <param name="writer">작성자</param> /// <param name="typeEnumerable">타입 열거 가능형</param> private void WriteClassesToFile(TextWriter writer, IEnumerable<JSONType> typeEnumerable) { bool inNamespace = false; bool rootNamespace = false; CodeWriter.WriteFileStart(this, writer); foreach(JSONType type in typeEnumerable) { if(UseNamespaces && inNamespace && rootNamespace != type.IsRoot && SecondaryNamespace != null) { CodeWriter.WriteNamespaceEnd(this, writer, rootNamespace); inNamespace = false; } if(UseNamespaces && !inNamespace) { CodeWriter.WriteNamespaceStart(this, writer, type.IsRoot); inNamespace = true; rootNamespace = type.IsRoot; } CodeWriter.WriteClass(this, writer, type); } if(UseNamespaces && inNamespace) { CodeWriter.WriteNamespaceEnd(this, writer, rootNamespace); } CodeWriter.WriteFileEnd(this, writer); } #endregion #region 파일에 클래스 쓰기 - WriteClassesToFile(filePath, typeEnumerable) /// <summary> /// 파일에 클래스 쓰기 /// </summary> /// <param name="filePath">파일 경로</param> /// <param name="typeEnumerable">타입 열거 가능형</param> private void WriteClassesToFile(string filePath, IEnumerable<JSONType> typeEnumerable) { using(StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8)) { WriteClassesToFile(writer, typeEnumerable); } } #endregion } } |
[TestProject 프로젝트]
▶ MainForm.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 |
using System; using System.IO; using System.Linq; using System.Windows.Forms; using TestLibrary; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 코드 작성자 배열 /// </summary> private readonly static ICodeWriter[] _codeWriterArray = new ICodeWriter[] { new CSharpCodeWriter(), new VisualBasicCodeWriter(), new TypeScriptCodeWriter() }; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 마지막 생성 문자열 /// </summary> private string lastGeneratedString; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); Load += Form_Load; FormClosing += Form_FormClosing; this.namespaceTextBox.TextChanged += namespaceTextBox_TextChanged; this.mainClassTextBox.TextChanged += mainClassTextBox_TextChanged; this.targetDirectoryPathButton.Click += targetDirectoryPathButton_Click; this.languageComboBox.SelectedIndexChanged += languageComboBox_SelectedIndexChanged; this.useNestedClassesRadioButton.CheckedChanged += useNestedClassesRadioButton_CheckedChanged; this.useSameNamespaceRadioButton.CheckedChanged += useSameNamespaceRadioButton_CheckedChanged; this.useDifferentNamespaceRadioButton.CheckedChanged += useDifferentNamespaceRadioButton_CheckedChanged; this.explicitDeserializationCheckBox.CheckedChanged += explicitDeserializationCheckBox_CheckedChanged; this.jsonTextBox.KeyDown += jsonTextBox_KeyDown; this.pasteButton.Click += pasteButton_Click; this.generateButton.Click += generateButton_Click; this.closeButton.Click += closeButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected //////////////////////////////////////////////////////////////////////////////// Function #region 키 DOWN 처리하기 - OnKeyDown(e) /// <summary> /// 키 DOWN 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnKeyDown(KeyEventArgs e) { if(e.KeyCode == Keys.F9) { e.Handled = true; Paste(); } base.OnKeyDown(e); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 폼 로드시 처리하기 - Form_Load(sender, e) /// <summary> /// 폼 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_Load(object sender, EventArgs e) { Properties.Settings settings = Properties.Settings.Default; (settings.UseProperties ? this.propertyRadioButton : this.fieldRadioButton ).Checked = true; (settings.InternalVisibility ? this.internalRadioButton : this.publicRadioButton).Checked = true; this.secondaryNamespaceTextBox.Text = settings.SecondaryNamespace; if(settings.NamespaceStrategy == 0) { this.useNestedClassesRadioButton.Checked = true; } else if(settings.NamespaceStrategy == 1) { this.useSameNamespaceRadioButton.Checked = true; } else { this.useDifferentNamespaceRadioButton.Checked = true; } this.languageComboBox.Items.AddRange(_codeWriterArray); int languageIndex = _codeWriterArray.ToList().FindIndex(x => x.GetType().Name == settings.Language); this.languageComboBox.SelectedIndex = languageIndex != -1 ? languageIndex : 0; this.singleFileCheckBox.Checked = settings.SingleFile; this.examplesInDocumentationCheckBox.Checked = settings.DocumentationExamples; UpdateStatus(); } #endregion #region 폼을 닫을 경우 처리하기 - Form_FormClosing(sender, e) /// <summary> /// 폼을 닫을 경우 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Form_FormClosing(object sender, FormClosingEventArgs e) { Properties.Settings settings = Properties.Settings.Default; settings.UseProperties = this.propertyRadioButton.Checked; settings.InternalVisibility = this.internalRadioButton.Checked; settings.SecondaryNamespace = this.secondaryNamespaceTextBox.Text; if(this.useNestedClassesRadioButton.Checked) { settings.NamespaceStrategy = 0; } else if(this.useSameNamespaceRadioButton.Checked) { settings.NamespaceStrategy = 1; } else { settings.NamespaceStrategy = 2; } if(!settings.UseSeparateNamespace) { settings.SecondaryNamespace = string.Empty; } settings.Language = this.languageComboBox.SelectedItem.GetType().Name; settings.SingleFile = this.singleFileCheckBox.Checked; settings.DocumentationExamples = this.examplesInDocumentationCheckBox.Checked; settings.Save(); } #endregion #region 네임스페이스 텍스트 박스 텍스트 변경시 처리하기 - namespaceTextBox_TextChanged(sender, e) /// <summary> /// 네임스페이스 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void namespaceTextBox_TextChanged(object sender, EventArgs e) { UpdateStatus(); } #endregion #region 메인 클래스 텍스트 박스 텍스트 변경시 처리하기 - mainClassTextBox_TextChanged(sender, e) /// <summary> /// 메인 클래스 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void mainClassTextBox_TextChanged(object sender, EventArgs e) { UpdateStatus(); } #endregion #region 타겟 디렉토리 경로 버튼 클릭시 처리하기 - targetDirectoryPathButton_Click(sender, e) /// <summary> /// 타겟 디렉토리 경로 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void targetDirectoryPathButton_Click(object sender, EventArgs e) { using(FolderBrowserDialog dialog = new FolderBrowserDialog()) { dialog.ShowNewFolderButton = true; dialog.SelectedPath = this.targetDirectoryPathTextBox.Text; dialog.Description = "생성 파일을 저장하기 위한 디렉토리를 선택해 주시기 바랍니다."; if(dialog.ShowDialog(this) == DialogResult.OK) { this.targetDirectoryPathTextBox.Text = dialog.SelectedPath; } } } #endregion #region 언어 콤보 박스 선택 인덱스 변경시 처리하기 - languageComboBox_SelectedIndexChanged(sender, e) /// <summary> /// 언어 콤보 박스 선택 인덱스 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void languageComboBox_SelectedIndexChanged(object sender, EventArgs e) { UpdateStatus(); } #endregion #region 중첩 클래스 사용 라디오 버튼 체크 변경시 처리하기 - useNestedClassesRadioButton_CheckedChanged(sender, e) /// <summary> /// 중첩 클래스 사용 라디오 버튼 체크 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void useNestedClassesRadioButton_CheckedChanged(object sender, EventArgs e) { UpdateStatus(); } #endregion #region 동일 네임스페이스 라디오 버튼 체크 변경시 처리하기 - useSameNamespaceRadioButton_CheckedChanged(sender, e) /// <summary> /// 동일 네임스페이스 라디오 버튼 체크 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void useSameNamespaceRadioButton_CheckedChanged(object sender, EventArgs e) { UpdateStatus(); } #endregion #region 다른 네임스페이스 라디오 버튼 체크 변경시 처리하기 - useDifferentNamespaceRadioButton_CheckedChanged(sender, e) /// <summary> /// 다른 네임스페이스 라디오 버튼 체크 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void useDifferentNamespaceRadioButton_CheckedChanged(object sender, EventArgs e) { UpdateStatus(); } #endregion #region 명시적 역직렬화 사용 체크 박스 체크 변경시 처리하기 - explicitDeserializationCheckBox_CheckedChanged(sender, e) /// <summary> /// 명시적 역직렬화 사용 체크 박스 체크 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void explicitDeserializationCheckBox_CheckedChanged(object sender, EventArgs e) { UpdateStatus(); } #endregion #region JSON 텍스트 박스 키 DOWN 처리하기 - jsonTextBox_KeyDown(sender, e) /// <summary> /// JSON 텍스트 박스 키 DOWN 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void jsonTextBox_KeyDown(object sender, KeyEventArgs e) { if(e.Control && e.KeyCode == Keys.A) { this.jsonTextBox.SelectionStart = 0; this.jsonTextBox.SelectionLength = this.jsonTextBox.TextLength; e.Handled = true; } } #endregion #region 붙여넣기 버튼 클릭시 처리하기 - pasteButton_Click(sender, e) /// <summary> /// 붙여넣기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void pasteButton_Click(object sender, EventArgs e) { Paste(); } #endregion #region 생성 버튼 클릭시 처리하기 - generateButton_Click(sender, e) /// <summary> /// 생성 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void generateButton_Click(object sender, EventArgs e) { if(this.namespaceTextBox.Text == string.Empty) { MessageBox.Show ( this, "네임스페이스를 지정해 주시기 바랍니다.", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information ); return; } if(this.targetDirectoryPathTextBox.Text == string.Empty) { MessageBox.Show ( this, "타겟 디렉토리 경로를 지정해 주시기 바랍니다.", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information ); return; } JSONClassGenerator generator = GetGenerator(); if(generator == null) { return; } try { generator.GenerateClasses(); } catch(Exception exception) { MessageBox.Show ( this, "코드를 생성할 수 없습니다 : " + exception.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } #endregion #region 닫기 버튼 클릭시 처리하기 - closeButton_Click(sender, e) /// <summary> /// 닫기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void closeButton_Click(object sender, EventArgs e) { Close(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 상태 업데이트하기 - UpdateStatus() /// <summary> /// 상태 업데이트하기 /// </summary> private void UpdateStatus() { if(this.secondaryNamespaceTextBox.Text.Contains("JsonTypes") || this.secondaryNamespaceTextBox.Text == string.Empty) { this.secondaryNamespaceTextBox.Text = this.namespaceTextBox.Text == string.Empty ? string.Empty : this.namespaceTextBox.Text + "." + "JsonTypes"; } this.secondaryNamespaceTextBox.Enabled = this.useDifferentNamespaceRadioButton.Checked; ICodeWriter writer = this.languageComboBox.SelectedItem as ICodeWriter; this.pascalCaseCheckBox.Enabled = !(writer is TypeScriptCodeWriter); this.explicitDeserializationCheckBox.Enabled = writer is CSharpCodeWriter; this.noHelperClassCheckBox.Enabled = this.explicitDeserializationCheckBox.Enabled && this.explicitDeserializationCheckBox.Checked; } #endregion #region 제너레이터 구하기 - GetGenerator() /// <summary> /// 제너레이터 구하기 /// </summary> /// <returns>제너레이터</returns> private JSONClassGenerator GetGenerator() { if(this.jsonTextBox.Text == string.Empty) { MessageBox.Show ( this, "JSON을 입력해 주시기 바랍니다.", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information ); this.jsonTextBox.Focus(); return null; } if(this.mainClassTextBox.Text == string.Empty) { MessageBox.Show ( this, "메인 클래스명을 입력해 주시기 바랍니다.", "INFORMATION", MessageBoxButtons.OK, MessageBoxIcon.Information ); return null; } JSONClassGenerator generator = new JSONClassGenerator(); generator.Example = this.jsonTextBox.Text; generator.InternalVisibility = this.internalRadioButton.Checked; generator.CodeWriter = this.languageComboBox.SelectedItem as ICodeWriter; generator.ExplicitDeserialization = this.explicitDeserializationCheckBox.Checked && generator.CodeWriter is CSharpCodeWriter; generator.Namespace = string.IsNullOrEmpty(this.namespaceTextBox.Text) ? null : this.namespaceTextBox.Text; generator.NoHelperClass = this.noHelperClassCheckBox.Checked; generator.SecondaryNamespace = this.useDifferentNamespaceRadioButton.Checked && !string.IsNullOrEmpty(this.secondaryNamespaceTextBox.Text) ? this.secondaryNamespaceTextBox.Text : null; generator.TargetDirectoryPath = this.targetDirectoryPathTextBox.Text; generator.UseProperties = this.propertyRadioButton.Checked; generator.MainClass = this.mainClassTextBox.Text; generator.UsePascalCase = this.pascalCaseCheckBox.Checked; generator.UseNestedClasses = this.useNestedClassesRadioButton.Checked; generator.ApplyObfuscationAttributes = this.applyObfuscationAttributeCheckBox.Checked; generator.SingleFile = this.singleFileCheckBox.Checked; generator.ExamplesInDocumentation = this.examplesInDocumentationCheckBox.Checked; return generator; } #endregion #region 붙여넣기 - Paste() /// <summary> /// 붙여넣기 /// </summary> private void Paste() { string jsonClipboard = Clipboard.GetText(TextDataFormat.UnicodeText | TextDataFormat.Text); if(jsonClipboard != this.lastGeneratedString) { string jsonClipboardTrimmed = jsonClipboard.Trim(); string jsonTextboxTrimmed = this.jsonTextBox.Text.Trim(); if((jsonClipboardTrimmed.StartsWith("{") || jsonClipboardTrimmed.StartsWith("[")) || !(jsonTextboxTrimmed.StartsWith("{") || jsonTextboxTrimmed.StartsWith("["))) { this.jsonTextBox.Text = jsonClipboard; } } JSONClassGenerator generator = GetGenerator(); if(generator == null) { return; } try { generator.TargetDirectoryPath = null; generator.SingleFile = true; using(StringWriter writer = new StringWriter()) { generator.Writer = writer; generator.GenerateClasses(); writer.Flush(); this.lastGeneratedString = writer.ToString(); Clipboard.SetText(this.lastGeneratedString); } } catch(Exception exception) { MessageBox.Show ( this, "코드를 생성할 수 없습니다 : " + exception.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } #endregion } } |