【问题标题】:Interfaces and JSON Serialization in .Net.Net 中的接口和 JSON 序列化
【发布时间】:2011-11-06 09:34:27
【问题描述】:

.Net 是否有任何 JSON 库允许我序列化/反序列化包含接口的类:

 public class MyClass
 {
    public IMyInterface1 Property1 {get;set;}
    public IMyInterface2 Property2 {get;set;}
 }

我意识到反序列化需要具体的类,所以我假设它们需要通过属性或作为方法调用的一部分来指定。

编辑:一项附加要求 - 它不应依赖 JSON 上的任何标记或特殊属性进行序列化/反序列化,因为有时我需要从第三方读取 JSON。

【问题讨论】:

    标签: .net json serialization interface


    【解决方案1】:

    托管使用jayrock 执行此操作。你只需要创建一个像这样的映射类:

    public class InterfaceImporter<TInterface, TClass> : IImporter where TClass : TInterface
    {
        public object Import(ImportContext context, JsonReader reader)
        {
            return(context.Import<TClass>(reader));
        }
    
        public Type OutputType
        {
            get { return (typeof(TInterface)); }
        }
    }
    

    然后使用此代码将接口映射到适当的类并反序列化:

    ImportContext context = new ImportContext();
    
    context.Register(new InterfaceImporter<IMyInterface1, MyClass1>());
    context.Register(new InterfaceImporter<IMyInterface2, MyClass2>());
    
    MyClass deserialized = context.Import<MyClass>(JsonText.CreateReader(json));
    

    【讨论】:

    • 类似的事情也可以用 JSON.Net 和 CustomCreationConverter 类来完成。
    【解决方案2】:

    您可以使用DataContractJsonSerializer 类,它允许您使用known types

    【讨论】:

    • 这适用于为每个对象添加一个“__type”属性的小麻烦。一个更大的问题是,反序列化过程显然取决于这个属性,有时我需要从不包含这些属性的第 3 方读取 JSON。我将编辑问题以澄清这一点。
    • @Badaro,您需要在序列化 JSON 中包含类型信息,否则您将无法将其反序列化。 DataContractJsonSerializer 使用 __type 属性。如果您以某种方式依赖不包含类型信息的第三方 JSON 提供程序,您不能期望反序列化回包含接口的对象。 .NET 的另一个流行的 JSON 序列化框架是 Json.NET (james.newtonking.com/pages/json-net.aspx)
    • 我同意,但通过 JSON 携带此信息并不是唯一的选择。我正在寻找允许我使用属性指定它或允许我实现一个类来执行接口 -> 类映射的东西。
    猜你喜欢
    • 2018-03-09
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多