Skip to content

Instantly share code, notes, and snippets.

@wallstop
Created November 11, 2020 02:13
Show Gist options
  • Save wallstop/52cb1fe0207c4b8339903827fd5bbf1c to your computer and use it in GitHub Desktop.
Save wallstop/52cb1fe0207c4b8339903827fd5bbf1c to your computer and use it in GitHub Desktop.
Serializer
using Assets.Scripts.Core.Extension;
using Assets.Scripts.Core.Serialization.JsonConverters;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace Assets.Scripts.Core.Serialization
{
internal static class SerializerEncoding
{
public static readonly Encoding Encoding = Encoding.Default;
public static readonly JsonConverter[] Converters =
{new StringEnumConverter(), Vector3Converter.Instance, Vector2Converter.Instance};
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Converters = Converters
};
}
public static class Serializer
{
public static T BinaryDeserialize<T>(byte[] data)
{
using (MemoryStream memoryStream = new MemoryStream(data))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
memoryStream.Position = 0;
return (T)binaryFormatter.Deserialize(memoryStream);
}
}
public static byte[] BinarySerialize<T>(T input)
{
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, input);
return memoryStream.ToArray();
}
}
public static T JsonDeserialize<T>(string data)
{
return JsonConvert.DeserializeObject<T>(data);
}
public static byte[] JsonSerialize(object input)
{
return JsonStringify(input).GetBytes();
}
public static string JsonStringify(object input, bool pretty = false)
{
return JsonConvert.SerializeObject(input, pretty ? Formatting.Indented : Formatting.None,
SerializerEncoding.Settings);
}
public static T ReadFromJsonFile<T>(string path)
{
string settingsAsText = File.ReadAllText(path, SerializerEncoding.Encoding);
return JsonDeserialize<T>(settingsAsText);
}
public static void WriteToJsonFile<T>(T input, string path)
{
string jsonAsText = JsonStringify(input);
File.WriteAllText(path, jsonAsText);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment