본문 바로가기

WPF/Nuget Package

[WPF - Nuget] JSON Serialize / Deserialize

JSON이란?

JSON(JavaScript Object Notation)

  • JavaScript Object Notation라는 의미의 축약어로 데이터를 저장하거 전송할때 많이 사용되는 경량의 Data 교환 형식
  • JavaScript에서 객체를 만들 때 사용하는 표현식을 의미한다
  • JSON 표현식은 사람과 기계 모두 이해하기 쉬우며 용량이 작아서, JSON이 XML을 대체해서 데이터 전송등에 많이 사용되고 있다.
  • JSON은 데이터 포멧일 뿐이며 어떠한 통신 방법도, 프로그래밍 분법도 아닌 단순 데이터를 표시하는 방법일 뿐이다.

    JSON 특징

  • 자바스크립트 객체 표기법과 아주 유사하다.
  • 자바 스크립의 문법과 유사하지만 텍스트 형식일 뿐이다.
  • 특정 언어에 종속되지 않으며, 대부분 프로그래밍 언어에서 JSON 포멧의 데이터를 핸들링 할 수 있는 라이브러리를 제공한다.

JSON의 문제점

  • ajax은 단순히 데이터만 아니라 JavaScript 그 자체도 전달할 수 있습니다. 이 말은 JSON데이터라고 해서 받았는데 단순 데이터가 아닌 JavaScript가 될수 있고, 그게 실행 될수 있다는 점입니다.(데이터 인줄 알고 받았는데 악성 스크립트가 될 수 있습니다.)

    이러한 단점을 보안하기 위해 순수하게 데이터만 추출하는 JSON 라이브러리가 따로 사용되기도 합니다.
    ajax란 synchronous JavaScript and XML의 약자입니다. JavaScript를 통해서 서버에 데이터를 비동기 방식으로 요청하는 것입니다.

JSON 형식

1. Name-Value형식의 쌍

  • { string Key : string value } 이런 형식을 가지고 있으며
  • Key값은 String 형식으로 "Key value" 과 같이 쌍 따움표(")사이에 Key값을 적어줘야 한다.
  • Value값으로 올수 있는 형식은 null, number, string, array, object, boolean이 있습니다.
  • 각 값의 구분자는 쉼표(,)를 이용합니다.
    { "key1" : "value01", "key2" : true }

    2. 값들의 순서화된 리스트 형식

  • 배열(Array)가 구현이 되어 있습니다.
  • [value1, value2] 형식으로 표현
    {
    "FirstName": "Yang",
    "LastName": "Junwoo",
    "Email": "junwoo@rootech.com",
    "hobby": ["Climbing","Running"],  
    }

Visual Studio에서 JSON Serialize 구현

XAML

    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button HorizontalAlignment="Right" Width="100" Height="30" Name="btnLoad" Margin="0,0,150,0" Content="Load" Click="btnLoad_Click"/>
        <Button HorizontalAlignment="Right" Width="100" Height="30" Name="btnSave" Margin="0,0,0,0" Content="Save" Click="btnSave_Click"/>
        <TextBox Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" x:Name="tbContents"/>
    </Grid>

Code

    private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Json files (*.json)|*.json|Text files (*.txt)|*.txt";
            if (ofd.ShowDialog() == true)
            {
                using (StreamReader sr = new StreamReader(ofd.FileName))
                {
                    var tmpStr = sr.ReadToEnd();
                    var pInfo = JsonConvert.DeserializeObject<PersonInfo>(tmpStr);
                    ShowPersonInfo(pInfo);
                }
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Json files (*.json)|*.json|Text files (*.txt)|*.txt";
            if (sfd.ShowDialog() == true)
            {
                WriteJson(sfd.FileName);

            }
        }
        private void WriteJson(string fileName)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer();
            serializer.NullValueHandling = NullValueHandling.Ignore; // Null 값 포함할 것인지            
            var pInfo = CreatePerson();
            using (StreamWriter sw = new StreamWriter(fileName))
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                serializer.Serialize(writer, pInfo, pInfo.GetType());
            }
            // 현재 화면에 표시
            var serialize = JsonConvert.SerializeObject(pInfo, Formatting.Indented);
            using (StreamWriter sw = new StreamWriter(fileName))
            {
                sw.Write(serialize);
            }
            tbContents.Text = serialize;
        }
        private void ShowPersonInfo(PersonInfo pInfo)
        {
            tbContents.Text = JsonConvert.SerializeObject(pInfo, Formatting.Indented);
        }
        private PersonInfo CreatePerson()
        {
            return new PersonInfo()
            {
                Name = "양뱅",
                Age = 33,
                Hobby = new string[] { "Climbing", "Running" },
                Pos = Position.Son,
                Family = new List<PersonInfo>()
                {
                    new PersonInfo
                    {
                        Name = "아부지",
                        Pos = Position.Father,
                        Age = 68,
                    },
                    new PersonInfo
                    {
                        Name = "어무니",
                        Pos = Position.Mother,
                        Age = 59,
                    },
                    new PersonInfo
                    {
                        Name = "누나",
                        Pos = Position.Sister,
                        Age = 35,
                    },
                }
            };
        }
    }
    public enum Position { Mother, Father, Son, Sister}
    public class PersonInfo
    {
        public string Name { get; set; }
        public int Age { get; set; }
        [JsonPropertyName("Position")]
        public Position Pos { get; set; }
        public string[] Hobby { get; set; }
        public List<PersonInfo> Family { get; set; }
    }

image

'WPF > Nuget Package' 카테고리의 다른 글

[WPF - NuGet] log4net (logger) 사용하기  (0) 2022.01.10