Deserialize to class - vb.net

I have a class Person which I can serialize with the following code, but I can’t figure out how to deserialize the file back to the class.
I would be grateful for help on this. Thank you.
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
I tried the following but it doesn’t work.
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

You should make sure your VB class object's property in accordance with the JSON key or JSON name.
For example using your sample JSON data in your comment:
Since your JSON data is not complete, I modify it as the following:
{"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"}]}
You can keep the above Json data in a file named my.txt, if you want to deserialize the Json data to VB object, your VB objects classes should be as the following two classes:
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
Please pay attention to that: the pList1 property of RootObject class is corresponding to the pList1 key or name in the JSON data.
Then you should be able to use the JsonConvert class to deserialize to 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

Related

Retrive Multiple Data Firebase in VB.Net

How to retrieve multiple data from firebase. I only know how to retrieve one data.
Here is my sample code.
Friend Class Employee_No_Fingerprint
Public Property code As Integer
Public Property last_name As String
Public Property first_name As String
Public Property middle_name As String
Public Property suffix As String
Public Property department_name As String
Public Property picture As String
Public Property fingerprint As String
Public Property upload As Integer
End Class
Private Sub GetAllEmployee()
Dim datEmployeeNoFingerprint As New Employee_No_Fingerprint()
Dim response As FirebaseResponse = clientFingerprint.Get("Employee_No_Fingerprint")
datEmployeeNoFingerprint = response.ResultAs(Of Employee_No_Fingerprint)()
End Sub
Private Sub GetAllEmployee()
Dim load As FirebaseResponse = client.Get("Employee_No_Fingerprint")
Dim data As Dictionary(Of String, POJO_Export) = JsonConvert.DeserializeObject(Of Dictionary(Of String, POJO_Export))(load.Body.ToString())
End Sub

Assigning values to an object and its nested object

I am a novice and am missing something simple. I have two Classes
Public Class Param
Public Property temperature As String
Public Property display As Boolean
Public Property storage As Boolean
Public Property reason As Boolean
Public Property stats As Object
Public Property errors As Object
End Class
Public Class getTemperature
Public Property method As String
Public Property params As Param()
Public Property id As String
End Class
I want to declare and assign values to the objects but I keep getting the error "Object reference not set to an instance of an object" when trying to assign values to items within param. I don't understand, I have created both the object GetTemperature and the object Params, what am I missing?
Dim GetTemp As New getTemperature
GetTemp.method = TextBoxMethod.Text
GetTemp.id = TextBoxID.Text
Dim params As New Param
params.temperature = "true"
'GetTemp.params(0) = params
I have also tried, but get the same response:
Dim GetTemp As New getTemperature
GetTemp.method = TextBoxMethod.Text
GetTemp.id = TextBoxID.Text
GetTemp.params(0).temperature = "True"
Try this:
Public Class Param
Public Property temperature As String
Public Property display As Boolean
Public Property storage As Boolean
Public Property reason As Boolean
Public Property stats As Object
Public Property errors As Object
End Class
Public Class getTemperature
Public Property method As String
Public Property params As List(Of Param)
Public Property id As String
Public Sub New()
params = New List(Of Param)
End Sub
End Class
So you could write something like:
Dim a As New getTemperature
a.params.Add(New Param)
It will work if you remove the parenthesis
Public Class getTemperature
Public Property method As String
Public Property params As Param
Public Property id As String
End Class
and then
Dim GetTemp As New getTemperature
GetTemp.method = TextBoxMethod.Text
GetTemp.id = TextBoxID.Text
Dim params As New Param
params.temperature = "true"
GetTemp.params = params

XmlSerializer not copying nested class values

I am using an XmlSerializer to DeepCopy an object, but somehow it's not copying the nested properties.
<TestClass()>
Public Class ObjectClonerTest
ReadOnly _target As IObjectCloner = New ObjectCloner()
<TestMethod()>
Public Sub DeepCopy_ComplexSourceObject_NestedObjectCopied()
Dim source As New SerialisableComplexGenericParameterHelper()
source.Data() = 1
source.ComplexValue.Data() = 2
Dim actual = _target.DeepCopy(source)
Assert.AreEqual(1, actual.Data())
Assert.AreEqual(2, actual.ComplexValue.Data())
End Sub
Public Class SerialisableComplexGenericParameterHelper
Public Property Data() As Integer
Public ReadOnly ComplexValue As New SerialisableGenericParameterHelper()
End Class
Public Class SerialisableGenericParameterHelper
Public Property Data() As Integer
End Class
End Class
The copy function:
Public Function DeepCopy(Of T)(ByVal pSource As T) As T Implements IObjectCloner.DeepCopy
Using memoryStream As New MemoryStream()
Dim binaryFormatter As New XmlSerializer(GetType(T))
binaryFormatter.Serialize(memoryStream, pSource)
memoryStream.Position() = 0
Return DirectCast(binaryFormatter.Deserialize(memoryStream), T)
End Using
End Function
XmlSerializer does not serialize ReadOnly fields. Removing ReadOnly fixed the issue.
ComplexValue is declared as:
Public ReadOnly ComplexValue As New SerialisableGenericParameterHelper()
This isn't a property - its only a field. Fixing this should sort it I think.

Need Help Initializing a Generic Property in VB.Net

I've created a request class. Here is an abbreviated version of it:
Public Class Request(Of T)
Private _Account As String
Public Property Account() As String
Get
Return _Account
End Get
Set(ByVal value As String)
_Account = value
End Set
End Property
Private _InnerRequest As T
Public Property InnerRequest() As T
Get
Return Me._InnerRequest
End Get
Set(ByVal value As T)
Me._InnerRequest = value
End Set
End Property
End Class
And then I have two other classes that I intend to use with this one - again, abbreviated
Public Class Individual
Public FirstName As String
Public LastName As String
Friend Sub New()
End Sub
End Class
And
Public Class Commercial
Public EntityName As String
Friend Sub New()
End Sub
End Class
Again, both of these are pretty abbreviated. The issue comes in when I attempt to use the properties of individual or commercial:
Dim Req As New Request(Of Individual)()
Req.InnerRequest.FirstName = "Herman" <-- Null Ref Exception
So... how do I get my inner request null ref exception kicked? I tried simply using Me._InnerRequest = New T in the New sub of Request, but no dice. Is there a way to handle this?
Req.InnerRequest must be set to an object instance of Individual first.
Req.InnerRequest = new Individual()
Req.InnerRequest.FirstName = "Herman"
Or create an instance for InnerRequest with the following modifications
Public Class Request(Of T As {New}) 'Classes of type T must have a public new constructor defined
::
Private _InnerRequest As New T() 'Creates a new class of type T when an instance is created of Request
And make the constructors of the other classes Public instead of Friend.
Than you can directly do
Dim Req As New Request(Of Individual)()
Req.InnerRequest.FirstName = "Herman"
#Barry already answered what the main problem is, but here's an alternate syntax if you prefer object initializers:
Req.InnerRequest = new Individual() With { FirstName = "Herman" }
Or, if you prefer, you could overload the constructor for your Individual class:
Dim individual As New Individual("Herman")
Req.InnerRequest = individual
With the Individual class looking like:
Public Class Individual
Public FirstName As String
Public LastName As String
Friend Sub New()
End Sub
Friend Sub New(firstName As String)
Me.FirstName = firstName
End Sub
End Class
You probably should consider restricting the T to some Entity class:
Public Class Request(Of T As Entity)
From which both Individual and Commercial will inherit:
Public Class Individual : Inherits Entity
Then maybe declare an overridable property Name of type String on this Entity class (which can be abstract/MustInherit), this should provide some flexibility. Otherwise you'd be having a hard time consuming your design pattern.

How to create a class that one of its object is in the type of another class in VB?

Following is my code
Class LIVandOSA
Public LIV_ As String
Public OSA_ As String
End Class
Class TestUnitID
Public SMPSdata As LIVandOSA
Public SMdata As LIVandOSA
Public COATEDBARdata As LIVandOSA
Public CLCLdata As LIVandOSA
Public Sub New(ByVal s As String)
SMPSdata.LIV_ = s
End Sub
End Class
In the main program, I wrote the following code to create a list of TestUnitID and add some element into it.
Dim a As New List(Of TestUnitID)
a.Add(New TestUnitID("a1.csv"))
a.Add(New TestUnitID("a2.csv"))
TextBox1.Text = a(0).SMPSdata.LIV_
But when I try to compile it, it gives me the following error
An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication1.exe
Additional information: Object reference not set to an instance of an object.
And the error cursor was pointing to the line SMPSdata.LIV_(s)
How should I fix this error?
The error is self-explanatory, you haven't initialized that object.
Since you are in the constructor it is a good place to initialize fields and properties:
Class TestUnitID
Public SMPSdata As LIVandOSA
Public SMdata As LIVandOSA
Public COATEDBARdata As LIVandOSA
Public CLCLdata As LIVandOSA
Public Sub New(ByVal s As String)
Me.SMPSdata = New LIVandOSA()
Me.SMdata = New LIVandOSA()
Me.COATEDBARdata = New LIVandOSA()
Me.CLCLdata = New LIVandOSA()
SMPSdata.LIV_(s)
End Sub
End Class
You should have initiate it before using the object, therefor you can use
Me.SMPSdata = New LIVandOSA()
...
to create a new object