ln.objects/serialization/json/JSONDeserializer.cs

76 lines
2.6 KiB
C#

using ln.json;
using ln.json.mapping;
using ln.logging;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace ln.objects.serialization.json
{
public class JSONDeserializer : Deserializer
{
ObjectStore ObjectStore;
public JSONMapper Mapper { get; }
public JSONDeserializer(ObjectStore objectStore)
{
ObjectStore = objectStore;
Mapper = new JSONMapper() { DefaultBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, DefaultMappingFlags = JSONObjectMappingFlags.FIELDS };
Mapper.OnRequestCustomUnserialization += Mapper_OnRequestCustomUnserialization;
Mapper.AddMappingFactory(
typeof(IList<>),
(Type targetType, out JSONMapping mapping) =>
{
mapping = (JSONMapping)Activator.CreateInstance(typeof(LazyListMapping<>).MakeGenericType(targetType.GetGenericArguments()),objectStore);
return false;
});
}
private bool Mapper_OnRequestCustomUnserialization(JSONValue json, Type targetType, out object o)
{
if (!(json is JSONNull) && !targetType.IsValueType && !targetType.IsInterface && Mapper.GetOrBuildMapping(targetType, out JSONMapping mapping) && mapping is JSONObjectMapping)
{
Guid uid = new Guid(Convert.FromBase64String((json as JSONString).Value));
return TryLookupObject(uid, targetType, out o);
}
o = null;
return false;
}
public override bool DeserializeObject(byte[] serializedBytes, ref object o)
{
throw new NotImplementedException();
/*
if (ObjectStore.DEBUG)
Logging.Log(LogLevel.DEBUG, "Deserializing: {0}", Encoding.UTF8.GetString(serializedBytes));
if (serializedBytes.Length == 0)
{
o = null;
return true;
}
if (Mapper.GetOrBuildMapping(targetType, out JSONMapping mapping))
{
JSONValue json = JSONParser.Parse(Encoding.UTF8.GetString(serializedBytes));
if (mapping is JSONObjectMapping objectMapping)
{
objectMapping.Apply(Mapper, json as JSONObject, o);
}
else
{
o = mapping.FromJson(Mapper, json);
}
return true;
}
throw new NotSupportedException();
*/
}
}
}