我有一个Person类,可以使用以下代码进行序列化,但是我不知道如何将文件反序列化回该类。 对此我将不胜感激。谢谢。
Imports Newtonsoft.Json
Imports Windows.Storage
Imports Windows.Storage.Streams
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Property Gender As String
End Class
Public NotInheritable Class MainPage
Inherits Page
Private p As Person
Private pList As New List(Of Person)
Private Async Sub Save()
Dim jsonContents As String = JsonConvert.SerializeObject(pList)
Dim localFolder As StorageFolder = ApplicationData.Current.LocalFolder
Dim textFile As StorageFile = Await localFolder.CreateFileAsync("a.txt", CreationCollisionOption.ReplaceExisting)
Using textStream As IRandomAccessStream = Await textFile.OpenAsync(FileAccessMode.ReadWrite)
Using textWriter As New DataWriter(textStream)
textWriter.WriteString(jsonContents)
Await textWriter.StoreAsync()
End Using
End Using
End Sub
End Class
我尝试了以下操作,但不起作用。
Private Async Sub GetData()
Dim localFolder As StorageFolder = ApplicationData.Current.LocalFolder
Dim textFile = Await localFolder.GetFileAsync("a.txt")
Dim readFile = Await FileIO.ReadTextAsync(textFile)
Dim obj As RootObject = JsonConvert.DeserializeObject(Of RootObject)(readFile)
End Sub
Public Class RootObject
'Public Property pList1() As List(Of Person)
Public Property Name() As String
Public Property Age() As Integer
Public Property Gender() As String
End Class
答案 0 :(得分:0)
您应确保您的VB类对象的属性符合 JSON键或 JSON名称。
例如,在注释中使用示例JSON数据:
由于您的JSON数据不完整,因此我将其修改如下:
{"pList1":[{"Name":"Henrik","Age":54,"Gender":"Mand"},{"Name":"Lone","Age":50,"Gender":"Kvinde"},{"Name":"Niels","Age":24,"Gender":"Mand"},{"Name":"Pernille","Age":26,"Gender":"Kvinde"}]}
您可以将上述Json数据保存在名为 my.txt 的文件中,如果要将Json数据反序列化为VB对象,则您的VB对象类应为以下两个类: / p>
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Property Gender As String
End Class
Public Class RootObject
Public Property pList1() As List(Of Person)
End Class
请注意:pList1
类的RootObject
属性与JSON数据中的 pList1 键或名称相对应。
然后,您应该可以使用JsonConvert
类反序列化为RootObject
。
Private Async Sub GetData()
Dim localFolder As StorageFolder = ApplicationData.Current.LocalFolder
Dim textFile = Await localFolder.GetFileAsync("my.txt")
Dim readFile = Await FileIO.ReadTextAsync(textFile)
Dim obj As RootObject = JsonConvert.DeserializeObject(Of RootObject)(readFile)
End Sub