using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace Revitalize.Framework.Utilities { /// /// Handles serialization of all objects in existence. /// public class Serializer { private JsonSerializer serializer; /// /// Constructor. /// public Serializer() { this.serializer = new JsonSerializer(); this.serializer.Formatting = Formatting.Indented; this.serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; this.serializer.NullValueHandling = NullValueHandling.Include; this.addConverter(new Framework.Utilities.Serialization.Converters.RectangleConverter()); this.addConverter(new Framework.Utilities.Serialization.Converters.Texture2DConverter()); //this.addConverter(new Framework.Utilities.Serialization.Converters.Vector2Converter()); } /// /// Adds a new converter to the json serializer. /// /// public void addConverter(JsonConverter converter) { this.serializer.Converters.Add(converter); } /// /// Deserializes an object from a .json file. /// /// /// /// public T Deserialize(string p) { string json = ""; foreach (string line in File.ReadLines(p)) { json += line; } using (StreamReader sw = new StreamReader(p)) using (JsonReader reader = new JsonTextReader(sw)) { var obj = this.serializer.Deserialize(reader); 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); } } } }