Convert DeserializeObject<object> to entity object doesnt work - serialization

I want to convert deserialized object to an entity object like this:
item.Data = JsonConvert.DeserializeObject<Object>(reader["Data"].ToString());
User user = item.Data as User;
but in second line, user set to null because item.Data cant convert to user, although following line works:
item.Data = JsonConvert.DeserializeObject<User>(reader["Data"].ToString());
why?
Note: User class is like this:
[Serializable]
public class User
{
private string fullName, userName;
private Enumes.UserType userType;
private Int64 userCode;
private Int32 userID;
private string userTypeDesc;
private string lastLoginIP;
private string lastLoginTime;
private List<Enumes.UserRole> userRole;
private List<UserAccessLevel> userAccessLevel;
private string mobilePhone;
private string codeMelli;
private string bDate;
private Enumes.UserCurrentStatus currentStatus;
private string currentIPAddress;
...}
UserAccessLevel is Serializable too.

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

Deserialize to class

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

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

Inheritance in Class

Question #1: Does this look like the proper way to use inheritance in my class? I plan to add methods to the PartPnl so that both RoughPnl and FinalPnl can use together by using their objects specific data.
Question #2: Using the default values in the properties seems like the best way to get values to my object from my main form. Is that the best way to do that or is there a different approach? The main form will be open the entire time but the object will only exist long enough to do what I need, like create RoughPnl->Use a Method or two->Add Panel to form->Done
Namespace PanelThings
Public Class PartPnl
Private TrvList As TreeView
Private BasePanel As Panel
Private Label As String = Main.cboLabel.Text
Private Qty As String = Main.cboQty.Text
Private Key As String = Nothing
Private HorizontalON As Boolean = Main.chkHorizontal.Checked
Private VerticalON As Boolean = Main.chkVertical.Checked
Private ScaleToPanelON As Boolean = Main.chkScaleToPanel.Checked
Private Scale As String = Main.cboScale.Text
Private RearrangeON As Boolean = Main.chkRearrange.Checked
Public Sub New(objTree As TreeView, basePanel As Panel)
TrvList = objTree
basePanel = basePanel
End Sub
End Class
Public Class FinalPnl
Inherits PartPnl
Private FinalWidth As String = Main.cboWidth.Text
Private FinalLength As String = Main.cboLength.Text
Private FinalColor As String = Main.picFinalColor.Tag
Private LabelON As Boolean = Main.chkLabelsON.Checked
Private SizeON As Boolean = Main.chkSizeON.Checked
Private PorSKey As String = "P"
Public Sub New(objTree As TreeView, basePanel As Panel)
MyBase.New(objTree, basePanel)
End Sub
End Class
Public Class RoughPnl
Inherits FinalPnl
Private RoughWidth As String = Main.cboWidthExtra.Text
Private RoughLength As String = Main.cboLengthExtra.Text
Private RoughColor As String = Main.picRoughColor.Tag
Private RoughON As Boolean = Main.chkRoughUnderFinal.Checked
Public Sub New(objTree As TreeView, basePanel As Panel)
MyBase.New(objTree, basePanel)
End Sub
End Class
End Namespace

Classes, references to save memory

I have a class as follows:
Public Class Courses
Public CoursesOfferedMAIN As New List(Of Category)
Public CoursesList As New List(Of Course)
Public SemsList As New List(Of Sem)
Public SubjectsList As New List(Of Subjects)
Public ExamsTypeList As New List(Of ExamType)
Public Class Category
Private CategoryName As String
Private Deleted As Boolean
Public Courses As New List(Of Course)
End Class
Public Class Course
Private CategoryName As String
Private CourseID As String
Private CourseName As String
Private Deleted As Boolean
Public Sems As New List(Of Sem)
End Class
Public Class Sem
Private CategoryName As String
Private CourseID As String
Private SemID As String
Private SemName As String
Private Deleted As Boolean
Public Subjects As New List(Of Subjects)
End Class
Public Class Subjects
Private CategoryName As String
Private CourseID As String
Private SemID As String
Private SubjectID As String
Private SubjectName As String
Private Deleted As Boolean
Public Exams As New List(Of ExamType)
End Class
Public Class ExamType
Private CategoryName As String
Private CourseID As String
Private SemID As String
Private SubjectID As String
Private ExamTypeID As String
Private ExamName As String
Private ExamMax As String
Private ExamMin As String
Private ExamPass As String
Private Deleted As Boolean
End Class
Public Sub UpdateLists()
CoursesList.Clear()
SemsList.Clear()
SubjectsList.Clear()
ExamsTypeList.Clear()
For Each Cat As Category In CoursesOfferedMAIN
For Each cour As Course In Cat.Courses
CoursesList.Add(cour)
For Each sems As Sem In cour.Sems
SemsList.Add(sems)
For Each subj As Subjects In sems.Subjects
SubjectsList.Add(subj)
For Each exam As ExamType In subj.Exams
ExamsTypeList.Add(exam)
Next
Next
Next
Next
Next
End Sub
End Class
There is no problem with the code how ever, I would like to know, in the process I am following, the number of subjects, couses, examsets etc would all get repeated in the specific type lists like SubjectsList, examstypelist etc.. since they are being copied over it would take more memory.
Hence, my question or doubt would be, is it possible to use the same as references instead of copying them over to lists to save memory, or are there any methods better than this?
You are already using references. Classes are reference types, so when you copy the objects you are actually just copying the references to the objects.