C#/ETC

JSON파일 프로젝트에 연동하기

Cathedral8293 2024. 8. 14. 15:57
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryPractice
{
    public class Program
    {
        static void Main(string[] args)
        {
            new App();
        }
    }
}
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Dictionary;

namespace DictionaryPractice
{
    public class App
    {
        public App()
        {

            Console.WriteLine("App 생성자를 생성하였습니다.");

            // Dictionary<키에 해당하는 형식, 값에 해당하는 형식>
            // 인스턴스화

            // 1. JSON파일 읽기 // ./ : 내가 있는 위치에 있는 파일을 읽어온다
            string json = File.ReadAllText("./weapon_data.json"); // 여기 자체가 값이므로 변수로 넣을 수 있다.
            Console.WriteLine(json);

            // 2. 역질렬화(문자열 -> 객체)
            // 역직렬화 대상 클래스를 생성 (매핑클래스)
            WeaponData[] weaponDatas = JsonConvert.DeserializeObject<WeaponData[]>(json); // json 데이터를 묶고있는 형식에 따라 타입 설정
             // 딕셔너리 컬렉션 인스턴스화
            Dictionary<int, WeaponData> dic = new Dictionary<int, WeaponData>();

            for (int i =0; i<weaponDatas.Length; i++)
            {
                WeaponData weaponData = weaponDatas[i];
                Console.WriteLine($"{weaponData.id}, {weaponData.name}");
                dic.Add(weaponData.id, weaponData);
            }

            // 딕셔너리의 요소의 값을 가져오기
            WeaponData data = dic[100];
            Console.WriteLine($"{data.id}, {data.name}");

            // 딕셔너리 요소를 순회
            // 반드시 foreach 사용
            foreach(KeyValuePair<int, WeaponData> pair in dic)
            {
                WeaponData elementData = pair.Value;
                Console.WriteLine("{0},{1}",pair.Key,elementData.name);  
            }

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

namespace Dictionary
{
    // 매핑클래스는 생성자를 만들지 않는다.
    public class WeaponData
    {
        public int id; // 맴버변수 선언시 데이터 테이블 순서대로 선언 및 동일한 변수 이름으로 선언
        public string name;
    }
}

'C# > ETC' 카테고리의 다른 글

자료구조 참고용  (0) 2025.04.20
궁금한 용어 정리  (0) 2025.04.15
Unity Mathf api 뜯어보기(진행)  (0) 2024.08.20
Git 관리하기  (0) 2024.08.20
JSON파일 제작하여 프로젝트에 연동 준비하기  (2) 2024.08.14