我想通过 json.net 序列化这段代码:
public interface ITestInterface
{
string Guid {get;set;}
}
public class TestClassThatImplementsTestInterface1
{
public string Guid { get;set; }
}
public class TestClassThatImplementsTestInterface2
{
public string Guid { get;set; }
}
public class ClassToSerializeViaJson
{
public ClassToSerializeViaJson()
{
this.CollectionToSerialize = new List<ITestInterface>();
this.CollectionToSerialize.add( new TestClassThatImplementsTestInterface2() );
this.CollectionToSerialize.add( new TestClassThatImplementsTestInterface2() );
}
List<ITestInterface> CollectionToSerialize { get;set; }
}
我想用 json.net 序列化/反序列化 ClassToSerializeViaJson。序列化工作正常,但反序列化给我这个错误:
Newtonsoft.Json.JsonSerializationException: Could not create an instance of type ITestInterface. Type is an interface or abstract class and cannot be instantiated.
那么我怎样才能反序列化 List<ITestInterface>
收藏?
最佳答案
我在尝试自己做这个时发现了这个问题。在我实现 Piotr Stapp's(Garath's) answer 之后,我被它看起来多么简单所震惊。如果我只是在实现一个方法,而这个方法已经传递了我想要实例化的确切类型(作为字符串),为什么库没有自动绑定(bind)它?
我实际上发现我不需要任何自定义绑定(bind)程序,只要我告诉它我正在做的事情,Json.Net 就能够完全满足我的需要。
序列化时:
string serializedJson = JsonConvert.SerializeObject(objectToSerialize, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
});
反序列化时:
var deserializedObject = JsonConvert.DeserializeObject<ClassToSerializeViaJson>(serializedJson, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
});
相关文档:Serialization Settings for Json.NET和 TypeNameHandling setting
关于c# - 反序列化接口(interface)实例的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15880574/