/* Json.cs * License: NCSA Open Source License * * Copyright: Merijn Hendriks * AUTHORS: * waffle.lord * Merijn Hendriks */ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.IO; using System.Linq; namespace Aki.Launcher.MiniCommon { public static class Json { public static string Serialize(T data) { return JsonConvert.SerializeObject(data); } public static T Deserialize(string json) { return JsonConvert.DeserializeObject(json); } public static void Save(string filepath, T data) { string json = Serialize(data); File.WriteAllText(filepath, json); } /// /// Save an object as json with formatting /// /// /// Full path to file /// Object to save to json file /// NewtonSoft.Json Formatting public static void SaveWithFormatting(string filepath, T data, Formatting format) { if (!File.Exists(filepath)) { Directory.CreateDirectory(Path.GetDirectoryName(filepath)); } File.WriteAllText(filepath, JsonConvert.SerializeObject(data, format)); } /// /// Load a class from file and don't save it if it doesn't exist. /// /// /// Full path to the file to load /// Allow null class property values to be returned. Default is false /// Returns a class object or null public static T LoadClassWithoutSaving(string filepath, bool AllowNullValues = false) where T : class { if (File.Exists(filepath)) { string json = File.ReadAllText(filepath); T classObject = JsonConvert.DeserializeObject(json); if (!AllowNullValues) { if (classObject.GetType().GetProperties().Any(x => x.GetValue(classObject) == null)) { return null; } } return classObject; } return null; } public static T Load(string filepath) where T : new() { if (!File.Exists(filepath)) { Save(filepath, new T()); return Load(filepath); } string json = File.ReadAllText(filepath); return Deserialize(json); } /// /// Get a single property back from a json file. /// /// /// Full Path to json file /// Name of property to return /// public static T GetPropertyByName(string FilePath, string PropertyName) { using (StreamReader sr = new StreamReader(FilePath)) { var tempData = JObject.Parse(sr.ReadToEnd()); if (tempData != null) { if (tempData[PropertyName].Value() is T requestedData) { return requestedData; } } } return default; } } }