UnityCommon/JsonRead/JsonReadBase.cs

65 lines
1.8 KiB
C#
Raw Normal View History

2024-12-11 17:10:53 +08:00
using Newtonsoft.Json;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
2025-01-08 13:03:55 +08:00
public class JsonReadBase : Base
2024-12-11 17:10:53 +08:00
{
/// <summary>
/// ͨ<>õ<EFBFBD>JSON<4F><4E><EFBFBD>غͽ<D8BA><CDBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/// </summary>
/// <typeparam name="T">Ŀ<><C4BF><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD></typeparam>
/// <param name="jsonFile">JSON<4F>ļ<EFBFBD><C4BC><EFBFBD>TextAsset</param>
/// <returns><3E><><EFBFBD><EFBFBD><EFBFBD>л<EFBFBD><D0BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD></returns>
public List<T> LoadJson<T>(TextAsset jsonFile)
{
if (jsonFile == null)
{
Debug.LogError("JSON<4F>ļ<EFBFBD>Ϊ<EFBFBD>ա<EFBFBD><D5A1><EFBFBD>ȷ<EFBFBD><C8B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȷ<EFBFBD><C8B7><EFBFBD>䡣");
return null;
}
try
{
string jsonText = jsonFile.text.Trim();
// ȷ<><C8B7>JSON<4F><4E><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʽ
if (!jsonText.StartsWith("["))
{
Debug.LogError("JSON<4F><4E>ʽ<EFBFBD><CABD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԥ<EFBFBD><D4A4>Ϊ<EFBFBD><CEAA><EFBFBD>顣");
return null;
}
// <20><><EFBFBD><EFBFBD><EFBFBD>л<EFBFBD>Ϊ<EFBFBD>б<EFBFBD>
List<T> dataList = JsonConvert.DeserializeObject<List<T>>(jsonText);
Debug.Log($"<22>ɹ<EFBFBD><C9B9><EFBFBD>JSON<4F><4E><EFBFBD><EFBFBD><EFBFBD>м<EFBFBD><D0BC><EFBFBD><EFBFBD><EFBFBD> {dataList.Count} <20><> {typeof(T).Name} <20><>Ŀ<EFBFBD><C4BF>");
return dataList;
}
catch (JsonException ex)
{
Debug.LogError($"JSON<4F><4E><EFBFBD><EFBFBD><EFBFBD>л<EFBFBD><D0BB><EFBFBD><EFBFBD><EFBFBD>: {ex.Message}");
return null;
}
}
/// <summary>
/// ͨ<>õ<EFBFBD><C3B5><EFBFBD>ʾ<EFBFBD><CABE><EFBFBD>ݷ<EFBFBD><DDB7><EFBFBD>
/// </summary>
/// <typeparam name="T"><3E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD></typeparam>
/// <param name="dataList"><3E><><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD></param>
/// <param name="dataTypeName"><3E><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ƣ<EFBFBD><C6A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>־<EFBFBD><D6BE><EFBFBD><EFBFBD></param>
public void DisplayData<T>(List<T> dataList)
{
if (dataList == null || dataList.Count == 0)
{
Debug.LogWarning($"û<><C3BB><EFBFBD><EFBFBD><EFBFBD>ݿ<EFBFBD><DDBF><EFBFBD>ʾ<EFBFBD><CABE>");
return;
}
foreach (var item in dataList)
{
string jsonString = JsonConvert.SerializeObject(item, Formatting.Indented);
Debug.Log($" {jsonString}");
}
}
}