minhd
12/31/2017 - 11:37 AM

DataSerializer.cs

using FullSerializer;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public static class DataSerializer
{
	private static readonly fsSerializer serializer = new fsSerializer();

        public static string Serialize<T>(object value, bool prettify = false)
        {
        	fsData data;
        	serializer.TrySerialize(typeof(T), value, out data).AssertSuccessWithoutWarnings();

		if (prettify)
            		return fsJsonPrinter.PrettyJson(data);
		else
			return fsJsonPrinter.CompressedJson(data);
        }

        public static T Deserialize<T>(string serializedState)
        {
        	fsData data = fsJsonParser.Parse(serializedState);

        	object deserialized = null;
        	serializer.TryDeserialize(data, typeof(T), ref deserialized).AssertSuccessWithoutWarnings();

        	return (T)deserialized;
        }
		
	public static byte[] SerializeToBytes(object value)
	{
		if (value == null)
			return null;
		
		var binaryFormatter = new BinaryFormatter();
		using (var ms = new MemoryStream())
		{
			binaryFormatter.Serialize(ms, value);
			return ms.ToArray();
		}
	}
		
	public static T DeserializeFromBytes<T>(byte[] bytes)
	{
		var binaryFormatter = new BinaryFormatter();
		using (var ms = new MemoryStream())
		{
			ms.Write(bytes, 0, bytes.Length);
			ms.Seek(0, SeekOrigin.Begin);
			return (T)binaryFormatter.Deserialize(ms);
		}
	}
}