From 303cd69bf8517a7cba5be87d6bd4ea260c85189a Mon Sep 17 00:00:00 2001 From: "aube.lee" Date: Sat, 1 Feb 2025 23:05:48 +0900 Subject: [PATCH] =?UTF-8?q?=EB=A6=AC=EC=8A=A4=ED=8A=B8=20=ED=98=95?= =?UTF-8?q?=ED=83=9C=EC=9D=98=20=EB=8D=B0=EC=9D=B4=ED=84=B0=20=EC=A0=80?= =?UTF-8?q?=EC=9E=A5=20=EB=A1=9C=EC=A7=81=20=EC=98=A4=EB=A5=98=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 | 54 ++++++++++++++----- 1 file changed, 41 insertions(+), 13 deletions(-) diff --git a/Gameton-06/Assets/Gameton/Scripts/Common/JSONLoader.cs b/Gameton-06/Assets/Gameton/Scripts/Common/JSONLoader.cs index dc74ab8b..804f469e 100644 --- a/Gameton-06/Assets/Gameton/Scripts/Common/JSONLoader.cs +++ b/Gameton-06/Assets/Gameton/Scripts/Common/JSONLoader.cs @@ -14,9 +14,16 @@ namespace TON [Serializable] private class Wrapper { - public List items; + public T items; } + /// JSON 배열을 강제로 Wrapper 형태로 감싸기 위한 함수 + private static string WrapArray(string jsonArray) + { + return "{\"items\":" + jsonArray + "}"; + } + + /// Resources 폴더에서 JSON 파일을 읽어 특정 데이터 타입으로 변환하는 함수 public static T LoadFromResources(string fileName) { @@ -33,17 +40,20 @@ namespace TON { string jsonText = jsonFile.text; - // T가 List<> 형태인지 검사 + // 🎯 [배열] JSON인지 확인 (배열이면 직접 변환) 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); // 리스트 추출 + if (jsonText.StartsWith("[")) + { + return JsonUtility.FromJson>(WrapArray(jsonText)).items; + } + else + { + // JSON이 Wrapper로 감싸져 있는지 확인 후 변환 + Wrapper wrapperInstance = JsonUtility.FromJson>(jsonText); + return wrapperInstance.items; + } } - // 일반 객체 변환 return JsonUtility.FromJson(jsonText); } @@ -72,11 +82,29 @@ namespace TON } /// 특정 데이터를 JSON 형식으로 저장하는 함수 - public static void SaveToFile(T data, string filePath) + public static void SaveToFile(T data, string fileName) { - string json = JsonUtility.ToJson(data, true); - File.WriteAllText(filePath, json); - Debug.Log($"데이터 저장 완료: {filePath}"); + string path = $"Assets/Gameton/Resources/{DATA_PATH}{fileName}.json"; + string json; + + // [리스트] 형식인지 확인 + if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List<>)) + { + // 리스트 데이터를 감싸는 래퍼 클래스를 사용하여 JSON 변환 + Wrapper wrapper = new Wrapper { items = data }; + json = JsonUtility.ToJson(wrapper, true); + } + else + { + // 일반 객체는 그대로 JSON 변환 + json = JsonUtility.ToJson(data, true); + } + + File.WriteAllText(path, json); + Debug.Log($"파일 저장 성공 ::: {fileName}.json"); } + + + } }