UnityCommon/JsonRead/JsonReadBase.cs
2025-01-08 13:03:55 +08:00

65 lines
1.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Newtonsoft.Json;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
public class JsonReadBase : Base
{
/// <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}");
}
}
}