Created
July 8, 2018 06:43
-
-
Save devmnj/ee21b0c22e37de2b19fb98811ce03131 to your computer and use it in GitHub Desktop.
Serializing and deserialize JSON Objects in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Please add reference to System.Web.Extention | |
class Accounts | |
{ | |
string acname; | |
string code; | |
public Accounts(string a,string c ) | |
{ | |
acname = a; code = c; | |
} | |
public Accounts() | |
{ | |
// TODO: Complete member initialization | |
} | |
public string CompanyName | |
{ | |
get | |
{ | |
return this.acname; | |
} | |
set | |
{ | |
this.acname = value; | |
} | |
} | |
public string Code | |
{ | |
get { return this.code; } | |
set | |
{ | |
this.code = value; | |
} | |
} | |
//Serialize Method | |
public static void InitializeJson() | |
{ | |
try | |
{ | |
Accounts[] ac = new Accounts [] { new Accounts( ), | |
new Accounts( ) | |
}; | |
ac[0]=new Accounts( "Office Account","A1" ); | |
ac[1].CompanyName = "Personal Account"; | |
ac[1].Code = "A2"; | |
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ac ); | |
// Write that JSON to txt file | |
File.WriteAllText("d:/dbjason.jason", json); | |
} | |
catch(Exception e) | |
{ | |
MessageBox.Show(e.Message.ToString()); | |
} | |
} | |
//Deserialize | |
ColumnHeader headers = new ColumnHeader(); | |
listView1.View = View.Details; | |
headers.Text = " "; | |
headers.Width = 0; | |
listView1.Columns.Add(headers); | |
headers = new ColumnHeader(); | |
headers.Text = "Code"; | |
headers.Width = 80; | |
listView1.Columns.Add(headers); | |
headers = new ColumnHeader(); | |
headers.Text = "Company"; | |
headers.Width = 300; | |
listView1.Columns.Add(headers); | |
listView1.FullRowSelect = true; | |
try | |
{ | |
Accounts[] a; | |
string json = File.ReadAllText("d:/dbjason.jason"); | |
a = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Accounts[]>(json); | |
ListViewItem tr_items = new ListViewItem(); | |
foreach (Accounts ac in a) | |
{ | |
tr_items = new ListViewItem(); | |
tr_items.SubItems.Add(ac.Code); | |
tr_items.SubItems.Add(ac.CompanyName); | |
listView1.Items.Add(tr_items); | |
} | |
} | |
catch | |
{ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment