C#교과서 마스터하기 47. XML과 JSON

min seung moon·2021년 7월 16일
0

C#

목록 보기
49/54

https://www.youtube.com/watch?v=78FjkJLbpZQ&list=PLO56HZSjrPTB4NxAsEP8HRk6YKBDLbp7m&index=82

1. XML과 JSON

  • 비동기 통신 AJAX(Asyncrous Javascript And XML) 사용을 위해 고안된 포맷 방식

01. XML(eXtensible Markup Language)

  • XML(eXtensible Markup Language)은 W3C에서 개발된, 다른 특수한 목적을 갖는 마크업 언어를 만드는데 사용하도록 권장하는 다목적 마크업 언어

02. JSON(JavaScript Object Notation)

  • JSON(제이슨[1], JavaScript Object Notation)은 속성-값 쌍( attribute–value pairs and array data types (or any other serializable value)) 또는 "키-값 쌍"으로 이루어진 데이터 오브젝트를 전달하기 위해 인간이 읽을 수 있는 텍스트를 사용하는 개방형 표준 포맷

2. 프로젝트(JSON)

01. 46에서 사용한 프로젝트 사용

02. JSON 파일 만들기


03. Newtonsoft.Json NuGet 패키지 다운로드

  • SChopTodoApp.Models


04. TodoRepositoryJson 작성

  • DeserializeObject
    • JSON => C# 객체
    • JsonConvert.DeserializeObject<List<Todo>>(todos);
  • SerializeObject
    • C# 객체 => JSON
    • JsonConvert.SerializeObject(_todos, Formatting.Indented);
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CShopTodoApp.Models
{
    public class TodoRepositoryJson : ITodoRepository
    {
        // 파일 경로
        private readonly string _filePath = "";

        // 인-메모리 역할을 해줄 컬렉션 생성
        private static List<Todo> _todos = new List<Todo>();

        public TodoRepositoryJson(string filePath = @"C:\Temp\Todos.json")
        {
            _filePath = filePath;
            var todos = File.ReadAllText(_filePath, Encoding.Default);
            // DeserializeObject JSON => C# 객체
            _todos = JsonConvert.DeserializeObject<List<Todo>>(todos);
        }

        public void Add(Todo model)
        {
            model.Id = _todos.Max(t => t.Id) + 1;
            _todos.Add(model);

            // 파일 저장
            // SerializeObject C# 객체 => JSON
            // Formatting.Indented, 들여쓰기
            string json = JsonConvert.SerializeObject(_todos, Formatting.Indented);
            File.WriteAllText(_filePath, json);
        }

        public List<Todo> GetAll()
        {
            return _todos.ToList();
        }
    }

}

05. UI에 Windows Forms App(.Net Core) 프로젝트 생성 및 Model 프로젝트 참조

  • CShopTodoApp.WinFormsApp


06. UI 구성

  • 속성 : F4
  • Form : Text : 할 일 목록
  • button : Text : 등록, Name : btnAdd
  • textbox : Name : txtTitle
  • checkbox : Text : 완료, Name : blnIsDone
  • label : Text : 할일, Name : lblTitle
  • lable : Text : 완료, Name : lblIsDone
  • Data,DataGridView



07. 이벤트 추가

  • Form1.cs
using CShopTodoApp.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CShopTodoApp.WinFormsApp
{
    public partial class Form1 : Form
    {
        private readonly ITodoRepository _repository;

        public Form1()
        {
            InitializeComponent();
            _repository = new TodoRepositoryJson(@"C:\Temp\Todos.json");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // dataGridView1에 데이터 출력
            DisplayData();
        }

        private void DisplayData()
        {
            this.dataGridView1.DataSource = _repository.GetAll();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string title = txtTitle.Text;
            bool isDone = blnIsDone.Checked;

            Todo todo = new Todo { Title = title, IsDone = isDone };
            _repository.Add(todo);

            DisplayData();
        }
    }
}




profile
아직까지는 코린이!

0개의 댓글