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

데이터 테이블 만들고 변환 및 불러오기 (연습)

by 이지훈26 2021. 9. 8.

using System;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace Helloworld1
{
    class App
    {
        public App()
        {
            string path = "./item_data.json";
            string json = File.ReadAllText(path);
            Console.WriteLine(json);

            //역직렬화 하기
            //json형식에 따라 형식 매개변수가 달라진다
            ItemData[] itemDatas = JsonConvert.DeserializeObject<ItemData[]>(json);

            //itemDatas의 값은 ItemData타입의 배열 인스턴스
            //배열 안에 요소 : ItemData클래스의 인스턴스 x 5

            //키-값 컬렉션에 데이터 넣기
            Dictionary<int, ItemData> dicItemDatas = new Dictionary<int, ItemData>();
            foreach(ItemData data in itemDatas)
            {
                dicItemDatas.Add(data.id, data);
            }

            //출력하기
            foreach (KeyValuePair<int, ItemData> pair in dicItemDatas)
            {
                Console.WriteLine("key: {0}, val: {1} {2}", pair.Key, pair.Value.name, pair.Value.damage);
            }
        }
    }
}


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

namespace Helloworld1
{
    class ItemData
    {
        public int id;
        public string name;
        public float damage;
    }
}