使用 Json.NET 反序列化保存的接口对象而不定义其实现类型会引发错误(当然),所以我编写了一个可重用的类:
public class MakeJsonConverter<TParent, TChild> : JsonConverter where TChild:TParent
{
private readonly Type _parent;
private Type _child;
public MakeJsonConverter()
{
_parent = typeof(TParent);
_child = typeof(TChild);
}
public override bool CanConvert(Type objectType)
{
return (objectType == _parent);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return serializer.Deserialize<TChild>(reader);
}
//This should never be called. Only reading from saved interface data was an issue without using a converter.
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
它工作正常,除了我传递给它的设置似乎没有被使用。实际上我不确定,我所知道的是 MissingMemberHandling.Error 不起作用。
public virtual string SerializeWithConverter<TParent, TChild>(TParent obj) where TChild : TParent
{
var settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new DefaultContractResolver
{
DefaultMembersSearchFlags =
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
},
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
//Settings important to this situation
MissingMemberHandling = MissingMemberHandling.Error,
Converters = new List<JsonConverter> { new MakeJsonConverter<TParent, TChild>() }
};
return JsonConvert.SerializeObject(obj, Formatting.Indented, settings);
}
我似乎无法弄清楚为什么会这样工作..谁能解释一下?