加了一个json读取的基类

This commit is contained in:
liuliang 2024-12-11 17:10:53 +08:00
parent 3c1f269eb5
commit 2c416146ad
3 changed files with 84 additions and 0 deletions

8
JsonRead.meta Normal file
View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a3626c36d2c3a2740b1b2305102cd551
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

65
JsonRead/JsonReadBase.cs Normal file
View File

@ -0,0 +1,65 @@
using Newtonsoft.Json;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
public class JsonReadBase : MonoBehaviour
{
/// <summary>
/// 通用的JSON加载和解析方法
/// </summary>
/// <typeparam name="T">目标数据类型</typeparam>
/// <param name="jsonFile">JSON文件的TextAsset</param>
/// <returns>反序列化后的数据列表</returns>
public List<T> LoadJson<T>(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<T> dataList = JsonConvert.DeserializeObject<List<T>>(jsonText);
Debug.Log($"成功从JSON数组中加载了 {dataList.Count} 个 {typeof(T).Name} 项目。");
return dataList;
}
catch (JsonException ex)
{
Debug.LogError($"JSON反序列化错误: {ex.Message}");
return null;
}
}
/// <summary>
/// 通用的显示数据方法
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="dataList">数据列表</param>
/// <param name="dataTypeName">数据类型名称,用于日志输出</param>
public void DisplayData<T>(List<T> 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}");
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5845527e066da024a953facb81e5b284
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: