c# - 反序列化接口(interface)实例的集合?

标签 c# json.net

我想通过 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.NETTypeNameHandling setting

关于c# - 反序列化接口(interface)实例的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15880574/

相关文章:

c# - 具有连接和计数的快速 linq 查询

c# - 使用 Json.NET 对派生自 Dictionary<string, T> 的类型 T 进行序列化和反序列化

c# - 对于 .Net 中的浮点值,如何防止未定义的值序列化为 0?

c# - C# 类如何处理 JSON 中的美元符号?

c# - 错误: Unable to load the service index for source <URL> when adding to Visual Studio

c# - 为什么 SWITCH...CASE 不采用 'char' ?

c# - 为 System.NotImplementedException/System.NotSupportedException 编写单元测试是一种好习惯吗

c# - CreateUserWithEmailAndPasswordAsync 错误 "Object reference not set to an instance of an object."

c# - 在不使用 $type 的情况下在 JSON.NET 中序列化字节数组

.net - JSON解码: Unexpected token: StartArray