开发者

WCF serializing objects with inheritance

Here's what I am trying to do. I have a WCF restful service, and I need to serialize multiple objects that inherit from the same class.

There is nothing in an开发者_JAVA技巧y of the base classes that needs to be serialized.

Here is a minimal demo that shows what I want to get to work:

<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

And here's the code that uses it:

<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

If I declare the List to be a list of TestObj1 instead, everything works.

Am I missing some crucial concept here?

EDIT:

The problem gains a new level of confusion by looking at this code:

    <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


What you are missing is a [KnownType] attribute.

WCF requires a way of knowing all possible types so that it could publish the WSDL.

Have a look here.

UPDATE

The problem is that List<T> is not covariant.

Use IEnumerable<T> instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜