using System; using System.IO; using Cysharp.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using PhxhSDK; using UnityEngine; namespace Framework { public static class JsonHelper { #if UNITY_EDITOR public static T LoadJson(string path) { var serializer = new JsonSerializer(); serializer.NullValueHandling = NullValueHandling.Ignore; if (File.Exists(path)) { using (var sr = new StreamReader(path)) { using (var reader = new JsonTextReader(sr)) { return serializer.Deserialize(reader); } } } else { return default(T); } } public static void SaveJson(string path, object obj) { JsonSerializer serializer = new JsonSerializer(); serializer.NullValueHandling = NullValueHandling.Ignore; // serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; var pathWithoutFile = Path.GetDirectoryName(path); if (!Directory.Exists(pathWithoutFile)) { Directory.CreateDirectory(pathWithoutFile); } if (File.Exists(path)) { File.Delete(path); } using (StreamWriter sw = File.CreateText(path)) using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, obj); } } #endif public static async UniTask LoadFromAddressble(string path) { var loadAsset = await AssetManager.Instance.LoadAssetAsync(path); if (loadAsset == null) { return default(T); } var text = loadAsset.text; return LoadJsonFromText(text); } private static T LoadJsonFromText(string text) { var serializer = new JsonSerializer(); serializer.NullValueHandling = NullValueHandling.Ignore; using (var sr = new StringReader(text)) { using (var reader = new JsonTextReader(sr)) { return serializer.Deserialize(reader); } } } } public class ColorJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, Color value, JsonSerializer serializer) { JObject colorObject = new JObject(); colorObject.Add("r", value.r); colorObject.Add("g", value.g); colorObject.Add("b", value.b); colorObject.Add("a", value.a); colorObject.WriteTo(writer); } public override Color ReadJson(JsonReader reader, System.Type objectType, Color existingValue, bool hasExistingValue, JsonSerializer serializer) { JObject colorObject = JObject.Load(reader); float r = colorObject.GetValue("r").ToObject(); float g = colorObject.GetValue("g").ToObject(); float b = colorObject.GetValue("b").ToObject(); float a = colorObject.GetValue("a").ToObject(); return new Color(r, g, b, a); } } }