0

我正在使用 .net WebApi 创建 Web 服务,并且当属性之一是派生类的 IEnumerable 时,将类序列化为 XML 时遇到问题。我尝试添加 knownType 赌注得到以下错误:

“错误 1 ​​属性 'KnownType' 在此声明类型上无效。它仅在 'class, struct' 声明上有效。”

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
}

类到连载

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

任何想法如何解决这个问题?谢谢!

4

1 回答 1

1

您可以尝试修改您的“orderDetailBase”类,如下所示:

[DataContract]
[KnownType(typeof(onlineOrderDetail))]
[KnownType(typeof(inStoreOrderDetail))]
public class orderDetailBase
{
   [DataMember]
   public int sequence { get; set; }
于 2013-03-18T19:02:23.120 回答