diff --git a/JsonRead.meta b/JsonRead.meta new file mode 100644 index 0000000..1ecaa73 --- /dev/null +++ b/JsonRead.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a3626c36d2c3a2740b1b2305102cd551 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/JsonRead/JsonReadBase.cs b/JsonRead/JsonReadBase.cs new file mode 100644 index 0000000..79945c8 --- /dev/null +++ b/JsonRead/JsonReadBase.cs @@ -0,0 +1,65 @@ +using Newtonsoft.Json; +using UnityEngine; +using System.IO; +using System.Collections.Generic; + +public class JsonReadBase : MonoBehaviour +{ + /// + /// 通用的JSON加载和解析方法 + /// + /// 目标数据类型 + /// JSON文件的TextAsset + /// 反序列化后的数据列表 + public List LoadJson(TextAsset jsonFile) + { + if (jsonFile == null) + { + Debug.LogError("JSON文件为空。请确保已正确分配。"); + return null; + } + + try + { + string jsonText = jsonFile.text.Trim(); + + // 确保JSON是数组格式 + if (!jsonText.StartsWith("[")) + { + Debug.LogError("JSON格式错误:预期为数组。"); + return null; + } + + // 反序列化为列表 + List dataList = JsonConvert.DeserializeObject>(jsonText); + Debug.Log($"成功从JSON数组中加载了 {dataList.Count} 个 {typeof(T).Name} 项目。"); + return dataList; + } + catch (JsonException ex) + { + Debug.LogError($"JSON反序列化错误: {ex.Message}"); + return null; + } + } + + /// + /// 通用的显示数据方法 + /// + /// 数据类型 + /// 数据列表 + /// 数据类型名称,用于日志输出 + public void DisplayData(List dataList) + { + if (dataList == null || dataList.Count == 0) + { + Debug.LogWarning($"没有数据可显示。"); + return; + } + + foreach (var item in dataList) + { + string jsonString = JsonConvert.SerializeObject(item, Formatting.Indented); + Debug.Log($" {jsonString}"); + } + } +} \ No newline at end of file diff --git a/JsonRead/JsonReadBase.cs.meta b/JsonRead/JsonReadBase.cs.meta new file mode 100644 index 0000000..f53e487 --- /dev/null +++ b/JsonRead/JsonReadBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5845527e066da024a953facb81e5b284 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: