From 2c416146adc2264ea398b707cd5628154e26f2ff Mon Sep 17 00:00:00 2001 From: liuliang <597380732@qq.com> Date: Wed, 11 Dec 2024 17:10:53 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E4=BA=86=E4=B8=80=E4=B8=AAjson?= =?UTF-8?q?=E8=AF=BB=E5=8F=96=E7=9A=84=E5=9F=BA=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JsonRead.meta | 8 +++++ JsonRead/JsonReadBase.cs | 65 +++++++++++++++++++++++++++++++++++ JsonRead/JsonReadBase.cs.meta | 11 ++++++ 3 files changed, 84 insertions(+) create mode 100644 JsonRead.meta create mode 100644 JsonRead/JsonReadBase.cs create mode 100644 JsonRead/JsonReadBase.cs.meta 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: