using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace StardustCore.Utilities.Serialization { public class Serializer { public static Serializer JSONSerializer; private JsonSerializer serializer; private JsonSerializerSettings settings; /// /// Constructor. /// public Serializer() { this.serializer = new JsonSerializer(); this.serializer.Formatting = Formatting.Indented; this.serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; this.serializer.NullValueHandling = NullValueHandling.Include; this.settings = new JsonSerializerSettings(); //this.serializer.Converters.Add(new Converters.TilePropertyConverter()); foreach (JsonConverter converter in this.serializer.Converters) { this.settings.Converters.Add(converter); } this.settings.Formatting = Formatting.Indented; this.settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; this.settings.NullValueHandling = NullValueHandling.Include; } /// /// Adds a new converter to the json serializer. /// /// The type of json converter to add to the Serializer. public void addConverter(JsonConverter converter) { this.serializer.Converters.Add(converter); } /// /// Deserializes an object from a .json file. /// /// The type of object to deserialize into. /// The path to the file. /// An object of specified type T. public T Deserialize(string p) { //string json = ""; //foreach (string line in File.ReadAllLines(p)) //{ //json += line; //} using (StreamReader sw = new StreamReader(p)) using (JsonReader reader = new JsonTextReader(sw)) { var obj = this.serializer.Deserialize(reader); return obj; } } /// /// Deserializes an object from a .json file. /// /// The type of object to deserialize into. /// The path to the file. /// An object of specified type T. public object Deserialize(string p, Type T) { /* string json = ""; foreach (string line in File.ReadAllLines(p)) { json += line; } */ using (StreamReader sw = new StreamReader(p)) using (JsonReader reader = new JsonTextReader(sw)) { object obj = this.serializer.Deserialize(reader, T); return obj; } } /// /// Serializes an object to a .json file. /// /// /// public void Serialize(string path, object o) { using (StreamWriter sw = new StreamWriter(path)) using (JsonWriter writer = new JsonTextWriter(sw)) { this.serializer.Serialize(writer, o); } } /// /// Converts objects to json form. /// /// /// public string ToJSONString(object o) { return JsonConvert.SerializeObject(o, this.settings); } /// /// Converts from json form to objects. /// /// /// /// public T DeserializeFromJSONString(string info) { return JsonConvert.DeserializeObject(info, this.settings); } /// /// Converts from json form to objects. /// /// /// /// public object DeserializeFromJSONString(string info, Type T) { return JsonConvert.DeserializeObject(info, T, this.settings); } } }