2011-08-29 67 views
3

有任何JSON庫爲.NET,讓我序列化/反序列化類包含接口:接口和JSON序列化在.net

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

我知道具體的類將是必要的反序列化,所以我假設它們需要通過屬性或作爲方法調用的一部分來指定。

編輯:另外一個要求 - 它不應該依賴任何標記或JSON的特殊屬性來進行序列化/反序列化,因爲有時我需要從第三方讀取JSON。

回答

1

Managed do do use this 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)); 
+0

類似的東西也可以用JSON.Net和CustomCreationConverter類來完成。 – Badaro

0

您可以使用DataContractJsonSerializer類,它允許您使用known types

+0

這適用於添加一個的小麻煩「 __type「屬性給每個對象。更大的問題是,顯然反序列化過程*取決於此屬性,有時我需要從不包含這些屬性的第三方讀取JSON。我將編輯這個問題來澄清這一點。 – Badaro

+0

@Badaro,在途中或其他你需要將類型信息包含到序列化JSON中,否則你將無法反序列化它。 DataContractJsonSerializer使用'__type'屬性。如果您依賴的第三方JSON提供程序不以某種方式包含類型信息,則無法期望將其反序列化回包含接口的對象。另一個流行的.NET JSON序列化框架是Json.NET(http://james.newtonking.com/pages/json-net.aspx) –

+0

我同意,但通過JSON攜帶這些信息不是唯一的選擇。我正在尋找允許我使用屬性指定它的東西,或者允許我實現一個類來執行接口 - >類映射。 – Badaro