Files
beyond/Assets/Scripts/Utils/JSONSerializer.cs
2024-11-20 15:21:28 +01:00

74 lines
2.3 KiB
C#

using System;
using FullSerializer;
namespace Beyond
{
public class JSONSerializer
{
fsSerializer m_serializer;
private static JSONSerializer s_instance;
public static JSONSerializer Instance {
get
{
if (s_instance != null)
return s_instance;
s_instance = new JSONSerializer();
s_instance.Initialize();
return s_instance;
}
}
public void Initialize()
{
m_serializer = new fsSerializer();
// m_serializer.AddConverter(new PickupSetConverter());
}
public void AddConverter(fsBaseConverter converter)
{
m_serializer.AddConverter((converter));
}
public string Serialize(Type type, object value) {
// serialize the data
fsData data;
m_serializer.TrySerialize(type, value, out data).AssertSuccessWithoutWarnings();
return fsJsonPrinter.PrettyJson(data);
// emit the data via JSON
//return fsJsonPrinter.CompressedJson(data);
}
public string Serialize<T>( object value) {
// serialize the data
fsData data;
m_serializer.TrySerialize(typeof(T), value, out data).AssertSuccessWithoutWarnings();
return fsJsonPrinter.PrettyJson(data);
// emit the data via JSON
//return fsJsonPrinter.CompressedJson(data);
}
public object Deserialize(Type type, string serializedState) {
// step 1: parse the JSON data
fsData data = fsJsonParser.Parse(serializedState);
// step 2: deserialize the data
object deserialized = null;
m_serializer.TryDeserialize(data, type, ref deserialized).AssertSuccessWithoutWarnings();
return deserialized;
}
public T Deserialize<T>(string serializedState) {
// step 1: parse the JSON data
fsData data = fsJsonParser.Parse(serializedState);
// step 2: deserialize the data
object deserialized = null;
m_serializer.TryDeserialize(data, typeof(T), ref deserialized).AssertSuccessWithoutWarnings();
return (T)deserialized;
}
}
}