2013-03-18 17 views
0

我正在使用.net WebApi創建Web服務,並且當其中一個屬性是派生類的IEnumerable時將序列化爲XML的問題。我曾嘗試加入knownType賭注獲取一個錯誤:如何在.net中對派生類的IEnumerable進行序列化WebApi

「錯誤1個屬性‘KnownType’不在此聲明類型有效 它是唯一有效的‘類,結構’的聲明。」

JSON序列化的作品完美,但對於XML我得到:

<Error> 
<Message>An error has occurred.</Message> 
<ExceptionMessage> 
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'. 
</ExceptionMessage> 
<ExceptionType>System.InvalidOperationException</ExceptionType> 
<StackTrace/> 
<InnerException> 
<Message>An error has occurred.</Message> 
<ExceptionMessage> 
Type 'test.order' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types. 
</ExceptionMessage> 
.... 

派生類例如

public class orderDetailBase 
{ 
    public int sequence { get; set; } 
    //.... more properties 
} 

public class onlineOrderDetail : orderDetailBase 
{ 
    public string ip { get; set; } 
    //.... more properties 
} 

public class inStoreOrderDetail : orderDetailBase 
{ 
    public string storeAddress { get; set; } 
    //.... more properties 
} 

類到serialzie

public class order 
{ 
    public int orderNumber{ get; set; } 
    //..... more 
    public IEnumerable<orderDetailBase> { get; set; } // Serializing this causes issues 

任何想法如何解決這個問題?謝謝!

回答

1

你可以嘗試修改你的「orderDetailBase」類象下面這樣:

[DataContract] 
[KnownType(typeof(onlineOrderDetail))] 
[KnownType(typeof(inStoreOrderDetail))] 
public class orderDetailBase 
{ 
    [DataMember] 
    public int sequence { get; set; } 
+0

我得到一個錯誤,當我嘗試。基本上說,knowtype只能用於類或結構。不適用於IEnumerable。 – jbrook10 2013-03-18 19:36:46

+0

嗯......你是否在屬性IEnumerable 上應用KnownType屬性?...如果是這樣,請將其刪除並重試... – 2013-03-18 19:38:39

+0

你說得對,我把它放在了錯誤的地方。我現在可以看到的XML,但不是爲我的4個詳細信息如下的數據 jbrook10 2013-03-18 20:16:28