我负责维护一个游戏系统,用户在本地缓存中保留JSON序列化POCO,以保留例如Character
的状态。
最新版本的代码更改了这些序列化对象的数据模型。特别是,创建了一个新界面。在将旧的字符副本反序列化为新代码时,这会产生问题。我试图通过自定义转换器解决这些问题,但我遇到了麻烦。
旧的序列化版本:
public class Character{
public Skill Parent {get;set;}
public Dictionary<string,Skill} Skills {get;set;}
}
public class Skill {
//normal stuff here.
}
新版本:
public class Character{
[JsonProperty, JsonConverter(typeof(ConcreteTypeConverter<Dictionary<string,Skill>>))]
public Dictionary<string,ISkill} Skills {get;set;}
}
public class Skill:ISkill {
//normal stuff here.
}
public interface ISkill{
//stuff that all skill-like things have here
}
我进一步定义了一个自定义转换器类(已阅读this和this,
但是我仍然遇到了对集合进行反序列化的问题。
public class Extensions
{
//a lot of serializer extensions here including the Deserialize method
private static readonly CustomSerializationBinder Binder = new CustomSerializationBinder();
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
TypeNameHandling = TypeNameHandling.Objects,
TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
Binder = Binder,
};
}
public class CustomSerializationBinder : DefaultSerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
return base.BindToType(assemblyName, typeName);
}
}
public class ConcreteTypeConverter<T> : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer,value); // serialization isnt't the problem.
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (typeof (T)==typeof(Dictionary<string,Skill>))
{
var retVal = new object();
if (reader.TokenType == JsonToken.StartObject)
{
T instance = (T)serializer.Deserialize(reader, typeof(T)); //crashes here
retVal = new List<T>() { instance };
return retVal;
}
}
return serializer.Deserialize<T>(reader);
}
public override bool CanConvert(Type objectType)
{
return true; // kind of a hack
}
}
所以我有一个旧 Dictionary<string,Skill>
我无法在我能看到的任何代码路径中将其转换为Dictionary<string,ISkill>
。我该如何解决这个问题?
答案 0 :(得分:0)
由于旧版JSON已包含所有对象(包括字典对象)的类型信息,因此您需要做的是剥离字典的类型信息,并允许代码控制反序列化的字典类型而不是JSON。
以下转换器应该完成这项工作:
public class IgnoreDictionaryTypeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.GetDictionaryKeyValueTypes().Count() == 1;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
existingValue = existingValue ?? serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
var obj = JObject.Load(reader);
obj.Remove("$type");
using (var subReader = obj.CreateReader())
{
serializer.Populate(subReader, existingValue);
}
return existingValue;
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public static class TypeExtensions
{
/// <summary>
/// Return all interfaces implemented by the incoming type as well as the type itself if it is an interface.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static IEnumerable<Type> GetInterfacesAndSelf(this Type type)
{
if (type == null)
throw new ArgumentNullException();
if (type.IsInterface)
return new[] { type }.Concat(type.GetInterfaces());
else
return type.GetInterfaces();
}
public static IEnumerable<Type[]> GetDictionaryKeyValueTypes(this Type type)
{
foreach (Type intType in type.GetInterfacesAndSelf())
{
if (intType.IsGenericType
&& intType.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
yield return intType.GetGenericArguments();
}
}
}
}
然后您可以在设置中添加它,或将其应用于相关的字典属性:
public class Character
{
[JsonConverter(typeof(IgnoreDictionaryTypeConverter))]
public IDictionary<string, ISkill> Skills { get; set; }
}
将来,您可能还希望禁用字典的类型信息发布,因为字典是集合,集合类型更好地由代码指定,而不是JSON:
public class Character
{
[JsonConverter(typeof(IgnoreDictionaryTypeConverter))]
[JsonProperty(TypeNameHandling = TypeNameHandling.None)]
public IDictionary<string, ISkill> Skills { get; set; }
}