■ JsonSerializer 클래스 : 스트림 직렬화/역직렬화 하기

----------------------------------------------------------------------------------------------------


TestProject.zip


JSONHelper.cs

 

 

using System.IO;

 

using Newtonsoft.Json;

 

namespace TestProject

{

    /// <summary>

    /// JSON 헬퍼

    /// </summary>

    public static class JSONHelper

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Static

        //////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 포매팅

        /// </summary>

        private static Formatting _formatting = Formatting.None;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Static

        //////////////////////////////////////////////////////////////////////////////// Public

 

        #region JSON 구하기 - GetJSON(sourceObject)

 

        /// <summary>

        /// JSON 구하기

        /// </summary>

        /// <param name="sourceObject">소스 객체</param>

        /// <returns>JSON 문자열</returns>

        public static string GetJSON(object sourceObject)

        {

            string json = JsonConvert.SerializeObject(sourceObject, _formatting);

 

            return json;

        }

 

        #endregion

        #region 객체 구하기 - GetObject<T>(json)

 

        /// <summary>

        /// 객체 구하기

        /// </summary>

        /// <typeparam name="T">타입</typeparam>

        /// <param name="json">JSON 문자열</param>

        /// <returns>객체</returns>

        public static T GetObject<T>(string json)

        {

            T targetObject = JsonConvert.DeserializeObject<T>(json);

 

            return targetObject;

        }

 

        #endregion

 

        #region 직렬화 하기 - Serialize(sourceObject, targetStream)

 

        /// <summary>

        /// 직렬화 하기

        /// </summary>

        /// <param name="sourceObject">소스 객체</param>

        /// <param name="targetStream">타겟 스트림</param>

        public static void Serialize(object sourceObject, Stream targetStream)

        {

            using(StreamWriter streamWriter = new StreamWriter(targetStream))

            {

                using(JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter))

                {

                    JsonSerializer jsonSerializer = new JsonSerializer();

 

                    jsonSerializer.Formatting = _formatting;

 

                    jsonSerializer.Serialize(jsonTextWriter, sourceObject);

 

                    jsonTextWriter.Flush();

                }

            }

        }

 

        #endregion

        #region 역직렬화 하기 - Deserialize<T>(sourceStream)

 

        /// <summary>

        /// 역직렬화 하기

        /// </summary>

        /// <typeparam name="T">타입</typeparam>

        /// <param name="sourceStream">소스 스트림</param>

        /// <returns>역직렬화 하기</returns>

        public static T Deserialize<T>(Stream sourceStream)

        {

            using(StreamReader streamReader = new StreamReader(sourceStream))

            {

                using(JsonTextReader jsonTextReader = new JsonTextReader(streamReader))

                {

                    JsonSerializer jsonSerializer = new JsonSerializer();

 

                    jsonSerializer.Formatting = _formatting;

 

                    T targetObject = jsonSerializer.Deserialize<T>(jsonTextReader);

 

                    return targetObject;

                }

            }

        }

 

        #endregion

    }

}

 

 

Program.cs

 

 

using System;

using System.Collections.Generic;

using System.IO;

 

namespace TestProject

{

    /// <summary>

    /// 프로그램

    /// </summary>

    class Program

    {

        /// <summary>

        /// 프로그램 시작하기

        /// </summary>

        static void Main()

        {

            // 소스 리스트를 생성한다.

            List<TestData> sourceList = new List<TestData>();

            

            for(int i = 0; i < 1000; i++)

            {

                sourceList.Add(new TestData { ID = i + 1, Name = "항목 " + (i + 1).ToString(), Grade = i % 5 + 1});

            }

 

 

            // 파일 스트림에 직렬화 한다.

            FileStream targetFileStream = new FileStream("d:\\result.json", FileMode.CreateNew);

 

            JSONHelper.Serialize(sourceList, targetFileStream);

 

 

            // 파일 스트림에서 역직렬화 한다.

            FileStream sourceFileStream = new FileStream("d:\\a.json", FileMode.Open);

 

            List<TestData> targetList = JSONHelper.Deserialize<List<TestData>>(sourceFileStream);

 

 

            // 결과를 출력한다.

            Console.WriteLine("소스 리스트 : {0}건", sourceList.Count);

            Console.WriteLine("타겟 리스트 : {0}건", targetList.Count);

        }

    }

}

 

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker
TAG