Deserializing an inherited class

  • Thread starter Thread starter cowznofsky
  • Start date Start date
C

cowznofsky

I have been using the below to serialize and deserialize my Foo class.
But I haven't been able
to inherit from Foo class (let's call it FooChild) and get it to work.
sXML is the result of the serialization. I want to instantiate a new
FooChild from DeserializeXML below, but when I try
I get an error saying it couldn't cast to FooChild. This also fails if
I try a DirectCast.


Public Function SerializeToXML() As String
Try
Dim o As New Foo
Dim serializer As XmlSerializer = New
XmlSerializer(GetType(Foo))
Dim sw As StringWriter = New StringWriter
serializer.Serialize(sw, o)
Return sw.ToString
Catch ex As Exception
ExceptionManager.Publish(ex)

End Try

End Function

Public Shared Function DeserializeXML(ByVal sXML As String) As Foo
Dim serializer As XmlSerializer = New
XmlSerializer(GetType(Foo))
Dim sr As StringReader = New StringReader(sXML)
Return CType(serializer.Deserialize(sr), Foo)
End Function
 
Ah well. I believe I see the situation. I created a base class
because I wanted to keep things simple when I serialized.
But I have to call the serialization function for the derived class,
and the serialization uses this class type. So in this scenario I
guess I would have to refer to the derived class from the base class,
although that doesn't feel right. Perhaps the gurus have another way
to do it.

My code below also contains an error in using object 'o'. Typically
'me' is used.
That was throwing a cast error, and for a moment I thought I got past
it..
 
Ok, I got it. I do stuff like this:

Public Function DeserializeXML(ByVal sXML As String) As Object
Dim serializer As XmlSerializer = New
XmlSerializer(Me.GetType())
Dim sr As StringReader = New StringReader(sXML)
Return serializer.Deserialize(sr)
End Function
 
Back
Top