如何在VB.NET中序列化List(of Object)?

时间:2017-07-27 06:58:26

标签: vb.net serialization uwp json.net windows-community-toolkit

我有一个用于创建Player的课程List(Of Player)。我需要在应用程序关闭时保存它。在Windows窗体中,我只是序列化,但在UWP中已经不再可能了,所以我不得不在谷歌上打了几十个小时而且我最终偶然发现了Microsoft.Toolkit.Uwp,然后Newtonsoft.Json,但我惨遭失败使用它们。我需要你的帮助!

假设我有一个小班:

Dim Name As String
Dim Score As Double
Public Class Player
    <JsonConstructor()>
    Public Sub New(Name As String, Score As Double) ' New with score
        Me.Name = Name
        Me.Score = Math.Max(1, Score)
    End Sub
End Class
Public Overrides Function ToString() As String ' ToString
    Return $"{Name} [{Score}]"
End Function

如何成功读写List(Of Player)

' Loading MainPage.xaml
Private Sub MainPage_Loading() Handles Me.Loading
    ReadAsync()
    MainFrame.Margin = New Thickness(0)
    Window.Current.Content = MainFrame
    MainFrame.Navigate(GetType(PlayerList), Players)
End Sub

' Read
Private Async Sub ReadAsync()
    Players = JsonConvert.DeserializeObject(Of List(Of Player))(Await FileIO.ReadTextAsync((Await StorageFolder.CreateFileAsync("players.json", CreationCollisionOption.OpenIfExists))))
    If Players Is Nothing Then
        Players = New List(Of Player)
        WriteAsync()
    End If
End Sub

' Write
Public Shared Async Sub WriteAsync()
    Await FileIO.WriteTextAsync(Await StorageFolder.CreateFileAsync("players.json", CreationCollisionOption.ReplaceExisting), JsonConvert.SerializeObject(Players, Formatting.Indented))
End Sub

' Loading PlayerList.xaml
Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
    ListBoxPlayers.Items.Clear()
    Players = e.Parameter
    For Each Player In Players
        ListBoxPlayers.Items.Add(Player)
    Next
End Sub

' Adding a new player in the interface
Private Sub ButtonAddPlayer_Click(sender As Button, e As RoutedEventArgs) Handles ButtonAddPlayer.Click
    ' ...
    ' Commit
    MainPage.Players.Add(New Player(TextBoxName.Text))
    ListBoxPlayers.Items.Add(MainPage.Players(MainPage.Players.Count - 1))
    MainPage.WriteAsync()
End Sub

所以这一切都令人困惑。当我通过界面添加播放器时,它会像平常一样进入我的ListBox。但是,当我关闭应用程序并重新打开它时,我会得到一些空对象。

List of different players Serialization didn't work!

我做了一些愤怒的测试以了解更多关于我的问题,结果我根本没有序列化,但我可能正确地反序列化。

Angry testing

1 个答案:

答案 0 :(得分:1)

我找到了它,结果发表在我的班级Player

我用过的东西:

Dim Name As String
Dim Score As Double

什么有效:

Public Name As String
Public Score As Double

我应该做些什么:

Public Property Name As String
Public Property Score As Double

我被教导在用Java编码时从不将变量设置为“公共”,我不知道Visual Basic中存在Property