[RESOLVED] Trying to Serialize a class
I'm trying to serialize this class:
Code:
<System.Serializable()> Public Class Person
Private _FirstName As String
Public Property FirstName() As String
Get
Return _FirstName
End Get
Set(ByVal value As String)
_FirstName = value
End Set
End Property
Private _LastName As String
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal value As String)
_LastName = value
End Set
End Property
End Class
Using this Class' .Serialize method:
Code:
Public Class Serialization
Public Function Serialize(ByVal FilePath As String, ByVal MyType As System.Type) As Boolean
Try
Using sw As New System.IO.StreamWriter(FilePath)
Dim ser As New Xml.Serialization.XmlSerializer(MyType)
ser.Serialize(sw, MyType)
End Using
Return True
Catch ex As Exception
Return False
End Try
End Function
End Class
Calling it like this:
Code:
Public Class Form1
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ser As New Serialization
Dim p As New Person With {.FirstName = "MyFirstName", .LastName = "MyLastName"}
ser.Serialize("C:\test\person.xml", p.GetType)
End Sub
End Class
But I get a "InvalidOperationException: There was an error generating the XML document" exception. I can't understand why the above does not work but if I change the .Serialize function to:
Code:
Public Class Serialization
Public Function Serialize(ByVal FilePath As String, ByVal MyType As Person) As Boolean
Try
Using sw As New System.IO.StreamWriter(FilePath)
Dim ser As New Xml.Serialization.XmlSerializer(MyType.GetType)
ser.Serialize(sw, MyType)
End Using
Return True
Catch ex As Exception
Return False
End Try
End Function
End Class
It works...
Re: Trying to Serialize a class
How can that first implementation possibly work? You're not passing the object you need to serialize into your Serialize method. You're passing in its type, not the object itself, so how can it ever be serialized?
The second argument to XmlSerializer.Serialize is the object to serialize. If you want it to serialize a Person then you have to pas it a Person object, not a Type object that represents the Person class.
Your Serialize method must take the object to serialize as an argument, not the type of the object. The type of the object will be determined from the object itself. Your method should look like this:
vb.net Code:
Public Class Serialization
Public Function Serialize(ByVal filePath As String, ByVal objectToSerialize As Object) As Boolean
Try
Using sw As New System.IO.StreamWriter(filePath)
Dim ser As New Xml.Serialization.XmlSerializer(objectToSerialize.GetType())
ser.Serialize(sw, objectToSerialize)
End Using
Return True
Catch ex As Exception
Return False
End Try
End Function
End Class
Does the renaming of the second parameter make it more obvious what's happening?
Re: Trying to Serialize a class
Yes, wow I'm an idiot. Thanks. I'd rep but your turn has not come around yet! :)