using System; using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace AibisDream.Utility { public static class JsonUtil { public const string JsonSuffix = ".json"; /// /// 按路径和Key加载 /// /// 路径 /// key /// 类型 /// Bean /// 错误 public static T ReadBean(string path, string key) { string json = File.ReadAllText(path); JObject jObject = JObject.Parse(json); if (jObject.ContainsKey(key)) { return jObject.ToObject(); } throw new Exception("没有找到对应的Key"); } /// /// 按路径加载Json /// /// /// /// public static T ReadBean(string path) { string json = File.ReadAllText(path); return JsonConvert.DeserializeObject(json); } /// /// 按路径加载Json /// /// 路径 /// Bean /// 目标Bean public static T[] ReadBeanArray(string path) { string json = File.ReadAllText(path); return JsonConvert.DeserializeObject(json); } /// /// 获取Json中的Key列表 /// /// 路径 /// key列表 public static string[] ReadKeys(string path) { string json = File.ReadAllText(path); JObject jObject = JObject.Parse(json); return jObject.Properties().Select(jProp => jProp.Name).ToArray(); } /// /// 保存Bean /// /// bean /// 路径 /// 类型 public static void SaveBean(T bean, string path) { string json = JsonConvert.SerializeObject(bean); File.WriteAllText(path, json); } /// /// 保存类 /// /// 对象 /// key /// 保存配置 /// 添加还是覆盖 /// 类型 public static void SaveBean(T bean, string key, string path, SaveMode saveMode = SaveMode.Add) { if (saveMode == SaveMode.Add && File.Exists(path)) { Dictionary originDic = JsonConvert.DeserializeObject>(path); originDic.Add(key, bean); string tempJson = JsonConvert.SerializeObject(originDic); File.WriteAllText(path, tempJson); } else { Dictionary tempDic = new Dictionary { { key, bean } }; string tempJson = JsonConvert.SerializeObject(tempDic); File.WriteAllText(path, tempJson); } } /// /// 自动把文件名转为Json /// /// 文件名 /// 已改为json的文件名 public static string FormatAsJsonPath(string fileName) { // 找到最后一个点的位置 int lastDotIndex = fileName.LastIndexOf('.'); // 如果没有点,说明没有扩展名 if (lastDotIndex == -1) { return fileName + JsonSuffix; } // 提取文件名(不包括扩展名) string fileNameWithoutExtension = fileName.Substring(0, lastDotIndex); // 返回新的文件名,使用 .json 作为扩展名 return fileNameWithoutExtension + JsonSuffix; } } public enum SaveMode { Replace, Add } }