From 0598cd1ce7c7a960f055acf3d4fa60fd240906d5 Mon Sep 17 00:00:00 2001 From: "aube.lee" Date: Sat, 1 Feb 2025 18:12:50 +0900 Subject: [PATCH] =?UTF-8?q?JSON=20Loader=20=EB=A6=AC=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=ED=98=95=ED=83=9C=20=ED=8C=8C=EC=8B=B1=20=ED=95=A0=20=EC=88=98?= =?UTF-8?q?=EC=9E=88=EB=8F=84=EB=A1=9D=20=EC=BD=94=EB=93=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Gameton/Scripts/Common/JSONLoader.cs | 35 +++++++++++++++++-- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/Gameton-06/Assets/Gameton/Scripts/Common/JSONLoader.cs b/Gameton-06/Assets/Gameton/Scripts/Common/JSONLoader.cs index 44c7b15f..dc74ab8b 100644 --- a/Gameton-06/Assets/Gameton/Scripts/Common/JSONLoader.cs +++ b/Gameton-06/Assets/Gameton/Scripts/Common/JSONLoader.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using System.Collections.Generic; using System.IO; @@ -9,19 +10,47 @@ namespace TON { private const string DATA_PATH = "GameData/"; + // 제네릭 리스트를 감싸기 위한 래퍼 클래스 + [Serializable] + private class Wrapper + { + public List items; + } + /// Resources 폴더에서 JSON 파일을 읽어 특정 데이터 타입으로 변환하는 함수 public static T LoadFromResources(string fileName) { + + if (fileName.EndsWith(".json")) + { + fileName = fileName.Replace(".json", ""); // 확장자 제거 + } + string path = DATA_PATH + $"{fileName}"; TextAsset jsonFile = Resources.Load(path); + if (jsonFile != null) { - return JsonUtility.FromJson(jsonFile.text); + string jsonText = jsonFile.text; + + // T가 List<> 형태인지 검사 + if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List<>)) + { + // JSON을 감싸는 래퍼 추가하여 변환 + string wrappedJson = "{\"items\":" + jsonText + "}"; + Type itemType = typeof(T).GetGenericArguments()[0]; // 리스트의 요소 타입 가져오기 + Type wrapperType = typeof(Wrapper<>).MakeGenericType(itemType); // Wrapper 생성 + object wrapperInstance = JsonUtility.FromJson(wrappedJson, wrapperType); // 변환 실행 + return (T)wrapperType.GetField("items").GetValue(wrapperInstance); // 리스트 추출 + } + + // 일반 객체 변환 + return JsonUtility.FromJson(jsonText); } else { - Debug.LogError($"JSON 파일을 찾을 수 없습니다: {fileName}"); - return default; // 기본값 반환 + Debug.LogError($"JSON 파일을 찾을 수 없습니다: {path}"); + return default; } }