2019-01-09 20:03:27 +08:00
|
|
|
using System;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.IO;
|
|
|
|
using System.Linq;
|
|
|
|
using System.Text;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using Newtonsoft.Json;
|
2019-01-11 03:09:51 +08:00
|
|
|
using Revitalize.Framework.Utilities.Serialization.ContractResolvers;
|
2019-01-09 20:03:27 +08:00
|
|
|
|
|
|
|
namespace Revitalize.Framework.Utilities
|
|
|
|
{
|
|
|
|
/// <summary>
|
|
|
|
/// Handles serialization of all objects in existence.
|
|
|
|
/// </summary>
|
|
|
|
public class Serializer
|
|
|
|
{
|
|
|
|
private JsonSerializer serializer;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Constructor.
|
|
|
|
/// </summary>
|
|
|
|
public Serializer()
|
|
|
|
{
|
|
|
|
this.serializer = new JsonSerializer();
|
|
|
|
this.serializer.Formatting = Formatting.Indented;
|
|
|
|
this.serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
|
|
|
|
this.serializer.NullValueHandling = NullValueHandling.Include;
|
|
|
|
|
2019-01-11 03:09:51 +08:00
|
|
|
this.serializer.ContractResolver = new NetFieldContract();
|
|
|
|
|
2019-01-09 20:03:27 +08:00
|
|
|
this.addConverter(new Framework.Utilities.Serialization.Converters.RectangleConverter());
|
|
|
|
this.addConverter(new Framework.Utilities.Serialization.Converters.Texture2DConverter());
|
2019-01-11 05:37:35 +08:00
|
|
|
//this.addConverter(new Framework.Utilities.Serialization.Converters.NetFieldConverter());
|
2019-01-09 20:03:27 +08:00
|
|
|
//this.addConverter(new Framework.Utilities.Serialization.Converters.Vector2Converter());
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Adds a new converter to the json serializer.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="converter"></param>
|
|
|
|
public void addConverter(JsonConverter converter)
|
|
|
|
{
|
|
|
|
this.serializer.Converters.Add(converter);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Deserializes an object from a .json file.
|
|
|
|
/// </summary>
|
|
|
|
/// <typeparam name="T"></typeparam>
|
|
|
|
/// <param name="p"></param>
|
|
|
|
/// <returns></returns>
|
|
|
|
public T Deserialize<T>(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<T>(reader);
|
|
|
|
return obj;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Serializes an object to a .json file.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="path"></param>
|
|
|
|
/// <param name="o"></param>
|
|
|
|
public void Serialize(string path, object o)
|
|
|
|
{
|
|
|
|
using (StreamWriter sw = new StreamWriter(path))
|
|
|
|
using (JsonWriter writer = new JsonTextWriter(sw))
|
|
|
|
{
|
|
|
|
this.serializer.Serialize(writer, o);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|