본문 바로가기
C#/수업내용

[ C# 11일차 ] JSON 직렬화/역직렬화 연습

by 왹져박사 2023. 1. 13.
728x90

//직렬화

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;


namespace Study12
{
    class App
    {
        //생성자
        public App()
        {
            Console.WriteLine("App");

            //직렬화
            //동적 배열(리스트) 생성
            List<Item> items = new List<Item>();

            //아이템 생성하고 배열에 추가
            items.Add(new Item("아대", 5));
            items.Add(new Item("창", 11));
            items.Add(new Item("너클", 5));
            items.Add(new Item("완드", 3));
            items.Add(new Item("스태프", 2));

            //직렬화
            //객체 (Item들을 저장하고 있는 List 인스턴스) -> JSON문자열
            //JSON문자열에서 배열은 []표현되면 객체는{}표현된다
            //List 안에 각 요소들은 객체이고 필드 키, 값 쌍으로 저장
            //ex){"name":"장검", "damage":"10"}
            //키는 문자열 형식""
            string json = JsonConvert.SerializeObject(items);
            Console.WriteLine(json);

            //직렬화 된 문자열 파일(.json)로 저장
            File.WriteAllText("./items.json", json);

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study12
{
    //[Serializable]            Newtonsoft.Json에서는 불필요
    class Item
    {
        //멤버 변수
        //직렬화 대상 필드는 반드시 public이어야 한다. 
        public int damage;      
        public string name;

        //생성자
        public Item(string name, int damage)
        {
            this.damage = damage;
            this.name = name;
        }
    }
}

//역직렬화

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;


namespace Study12
{
    class App
    {
        //생성자
        public App()
        {
            Console.WriteLine("App");

            //역직렬화
            //JSON문자열->객체
            //우리가 저장한 JSON문자열은 리스트(배열)이므로 배열행태로 역직렬화 되어야 함

            //파일 읽기
            string json = File.ReadAllText("./items.json");

            //파일에서 읽은 json 문자열 출력
            Console.WriteLine(json);

            //역직렬화
            Item[] items =  JsonConvert.DeserializeObject<Item[]>(json);

            //역직렬화 된 객체 출력
            Console.WriteLine(items.Length);
            foreach(Item item in items)
            {
                Console.WriteLine("{0}, {1}", item.name, item.damage);
            }

            //JSON문자열은 키/값 저장이므로
            //키/값을 저장하는 컨테이너(컬렉션) dictionary에 저장
            //키가 중복되서는 안된다. 

        }
    }
}

728x90