■ 다양한 타입의 JSON 직렬화 데이터를 저장하고 복구하는 방법을 보여준다.
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 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 |
using System; using System.Reflection; /// <summary> /// JSON 항목 /// </summary> public class JSONItem { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 타입 - Type /// <summary> /// 타입 /// </summary> public Type Type { get; set; } #endregion #region JSON - JSON /// <summary> /// JSON /// </summary> public string JSON { get; set; } #endregion } #region JSON 항목 구하기 - GetJSONItem(sourceObject) /// <summary> /// JSON 항목 구하기 /// </summary> /// <param name="sourceObject">소스 객체</param> /// <returns>JSON 항목</returns> public JSONItem GetJSONItem(object sourceObject) { if(sourceObject == null) { return null; } Type sourceType = sourceObject.GetType(); MethodInfo method = typeof(Newtonsoft.Json.JsonConvert).GetMethods().First ( m => m.Name == "SerializeObject" && m.GetParameters().Length == 1 && m.IsStatic && m.GetParameters()[0].ParameterType == typeof(object) ); string json = method.Invoke(null, new[] { sourceObject }) as string; JSONItem jsonItem = new JSONItem() { Type = sourceType, JSON = json }; return jsonItem; } #endregion #region 객체 구하기 - GetObject(jsonItem) /// <summary> /// 객체 구하기 /// </summary> /// <param name="jsonItem">JSON 항목</param> /// <returns>객체</returns> public object GetObject(JSONItem jsonItem) { MethodInfo method1 = typeof(Newtonsoft.Json.JsonConvert).GetMethods().First ( m => m.Name == "DeserializeObject" && m.GetParameters().Length == 1 && m.IsStatic && m.IsGenericMethodDefinition && m.GetParameters()[0].ParameterType == typeof(string) ); MethodInfo method2 = method1.MakeGenericMethod(new[] { jsonItem.Type }); return method2.Invoke(null, new[] { jsonItem.JSON }); } #endregion |
※ 비주얼 스튜디오 NuGet 패키지 관리에서 Newtonsoft.Json을 설치한다.