N. Henrik Lauridsen Ответов: 2

Сериализация /десериализация класса


Hi,

I need help on serializing /deserializing a class.
My class:
<Serializable()>
Public Class Scanner
    Public Property ScannerID As String
    Public Property ScannerText As String

    Private Sub New() ' Vigtigt ellers er det ikke muligt at serialize

    End Sub

    Public Sub New(ByVal sScanID As String, ByVal sScanText As String)
        ScannerID = sScanID
        ScannerText = sScanText
    End Sub

    Public Overrides Function toString() As String
        Return ScannerID.ToString & ", " & ScannerText.ToString
    End Function
End Class

В модуле
Public lstScanner As New List(Of Scanner)

Я использую список в качестве источника данных для ComboBox
Список заполняется из текста ComboBox и текстового поля
lstScanner.Add(New Scanner(cboScanID.Text, txtScanText.Text))

My goal is to save the data on application exit and reuse them on application start.
I succeed to save the data but cannot figure out how to deserialize them.
Public Sub SaveScanner(ByVal pathFile As String, ByVal className As List(Of Scanner)) 'className As String)
        'Serialize object (class) to an XML file, via the use of StreamWriter

        Dim objStreamWriter As New StreamWriter(pathFile)
        Dim xsSerialize As New XmlSerializer(className.GetType) 'Determine what object types are present

        xsSerialize.Serialize(objStreamWriter, className) 'Save
        objStreamWriter.Close() 'Close File
    End Sub
Thank you in advance


Что я уже пробовал:

Public Sub SaveScanner(ByVal pathFile As String, ByVal className As List(Of Scanner)) 'className As String)
    'Serialize object (class) to an XML file, via the use of StreamWriter

    Dim objStreamWriter As New StreamWriter(pathFile)
    Dim xsSerialize As New XmlSerializer(className.GetType) 'Determine what object types are present

    xsSerialize.Serialize(objStreamWriter, className) 'Save
    objStreamWriter.Close() 'Close File
End Sub

2 Ответов

Рейтинг:
16

Richard Deeming

Множество примеров в документации:
Примеры сериализации XML | Microsoft Docs[^]

Dim xsSerialize As New XmlSerializer(GetType(List(Of Scanner)))
Using fs As Stream = IO.File.OpenRead(path)
    Return DirectCast(xsSerialize.Deserialize(fs), List(Of Scanner))
End Using


N. Henrik Lauridsen

Привет Ричард,
Это сработало. Большое спасибо.

Рейтинг:
0

Gerry Schmitz

Вы не можете сериализовать коллекцию напрямую; ей нужен "родитель" / корень. например (в c#)

[DataContract()]
public class FengShuiStorage : IExtensibleDataObject {

   public ExtensionDataObject ExtensionData { get; set; }

   [DataMember()]
   public List<PersonDetails> Persons { get; set; } = new List<PersonDetails>();

   [DataMember()]
   public DateTime LastModified { get; set; }

}  // end class.