WCF序列化具有继承的对象

时间:2011-04-12 17:58:34

标签: wcf serialization inheritance

这是我想要做的。我有一个WCF restful服务,我需要序列化从同一个类继承的多个对象。

任何基类中都不需要序列化。

这是一个最小的演示,展示了我想要工作的内容:

<DataContract()>
Public Class BaseObj

    <DataMember()>
    Public ID As Integer

    Public Sub New(ByVal idval As Integer)
        ID = idval
    End Sub

End Class

<DataContract()>
Public Class TestObj1
    Inherits BaseObj

    Public Sub New(ByVal id As Integer)
        MyBase.New(id)
    End Sub

End Class

' Different from TestObj1 in real life
<DataContract()>
Public Class TestObj2
    Inherits BaseObj

    Public Sub New(ByVal id As Integer)
        MyBase.New(id)
    End Sub

End Class

以下是使用它的代码:

<ServiceContract()>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
<ServiceBehavior(InstanceContextMode:=InstanceContextMode.PerCall)>
Public Class Service1

    <WebGet(ResponseFormat:=WebMessageFormat.Json, UriTemplate:="Test?reqReportID={reqReportID}")>
    Public Function GetCollection(ByVal reqReportID As Integer) As List(Of BaseObj)

        Dim myObjs As New List(Of BaseObj)
        myObjs.Add(New TestObj1(20))
        myObjs.Add(New TestObj2(20))
        Return myObjs

    End Function

End Class

如果我将列表声明为TestObj1的列表,则一切正常。

我在这里错过了一些关键概念吗?

编辑:

通过查看此代码,问题会出现新的混乱:

    <WebGet(ResponseFormat:=WebMessageFormat.Json, UriTemplate:="Test?reqReportID={reqReportID}")>
    Public Function GetCollection(ByVal reqReportID As Integer) As BaseObj()

        Dim myObjs As New List(Of BaseObj)
        myObjs.Add(New TestObj1(20))
        myObjs.Add(New TestObj2(20))

        '   This guy works. Yields correct result of [{"ID":20},{"ID":20}] )
        Dim testStr As String = New JavaScriptSerializer().Serialize(myObjs.ToArray())

        '   But this guy still has problems...
        Return myObjs.ToArray()

    End Function

1 个答案:

答案 0 :(得分:1)

您缺少的是[KnownType]属性。

WCF需要一种了解所有可能类型的方法,以便它可以发布WSDL。

看看here

更新

问题是List<T> 不协变

改为使用IEnumerable<T>