From d1080a8b2b54c777a446f08d9ecd5b76b4b2561a Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Mon, 13 Feb 2017 00:13:29 -0500 Subject: move core JSON logic out of mod helper (#199) This lets SMAPI parse manifest.json files without a mod helper, so we can pass the mod name into the helper. --- .../Framework/Serialisation/JsonHelper.cs | 73 ++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs (limited to 'src/StardewModdingAPI/Framework/Serialisation') diff --git a/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs b/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs new file mode 100644 index 00000000..3809666f --- /dev/null +++ b/src/StardewModdingAPI/Framework/Serialisation/JsonHelper.cs @@ -0,0 +1,73 @@ +using System; +using System.IO; +using Newtonsoft.Json; +using StardewModdingAPI.Advanced; + +namespace StardewModdingAPI.Framework.Serialisation +{ + /// Encapsulates SMAPI's JSON file parsing. + public class JsonHelper + { + /********* + ** Accessors + *********/ + /// The JSON settings to use when serialising and deserialising files. + private readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + ObjectCreationHandling = ObjectCreationHandling.Replace // avoid issue where default ICollection values are duplicated each time the config is loaded + }; + + + /********* + ** Public methods + *********/ + /// Read a JSON file. + /// The model type. + /// The absolete file path. + /// The mod helper to inject for instances. + /// Returns the deserialised model, or null if the file doesn't exist or is empty. + public TModel ReadJsonFile(string fullPath, IModHelper modHelper) + where TModel : class + { + // read file + string json; + try + { + json = File.ReadAllText(fullPath); + } + catch (Exception ex) when (ex is DirectoryNotFoundException || ex is FileNotFoundException) + { + return null; + } + + // deserialise model + TModel model = JsonConvert.DeserializeObject(json, this.JsonSettings); + if (model is IConfigFile) + { + var wrapper = (IConfigFile)model; + wrapper.ModHelper = modHelper; + wrapper.FilePath = fullPath; + } + + return model; + } + + /// Save to a JSON file. + /// The model type. + /// The absolete file path. + /// The model to save. + public void WriteJsonFile(string fullPath, TModel model) + where TModel : class + { + // create directory if needed + string dir = Path.GetDirectoryName(fullPath); + if (!Directory.Exists(dir)) + Directory.CreateDirectory(dir); + + // write file + string json = JsonConvert.SerializeObject(model, this.JsonSettings); + File.WriteAllText(fullPath, json); + } + } +} -- cgit