■ JsonConvert 클래스의 SerializeObject/DeserializeObject 정적 메소드를 사용해 JSON 직렬화/역직렬화하는 방법을 보여준다.
▶ JSONHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
using System.Threading.Tasks; using Newtonsoft.Json; namespace TestProject; /// <summary> /// JSON 헬퍼 /// </summary> public static class JSONHelper { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 직렬화하기 (비동기) - SerializeAsync(item) /// <summary> /// 직렬화하기 (비동기) /// </summary> /// <param name="item">항목</param> /// <returns>JSON 문자열 태스크</returns> public static async Task<string> SerializeAsync(object item) { return await Task.Run<string> ( () => { return JsonConvert.SerializeObject(item); } ); } #endregion #region 역직렬화하기 (비동기) - DeserializeAsync<TItem>(json) /// <summary> /// 역직렬화하기 (비동기) /// </summary> /// <typeparam name="TItem">항목 타입</typeparam> /// <param name="json">JSON 문자열</param> /// <returns>항목 태스크</returns> public static async Task<TItem> DeserializeAsync<TItem>(string json) { return await Task.Run<TItem> ( () => { return JsonConvert.DeserializeObject<TItem>(json); } ); } #endregion } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> async static Task Main() { Dictionary<string, string> dictionary1 = new Dictionary<string, string>(); dictionary1.Add("1", "서울"); dictionary1.Add("2", "인천"); dictionary1.Add("3", "수원"); string json = await JSONHelper.SerializeAsync(dictionary1); Console.WriteLine(json); // {"1":"서울","2":"인천","3":"수원"} Dictionary<string, string> dictionary2 = await JSONHelper.DeserializeAsync<Dictionary<string, string>>(json); Console.WriteLine(dictionary2.Count); // 3 } #endregion } |