Reading and Writing Json objects in C#


The Account class

Build simple class Accounts with properties which keep records

Please include following library System.Web.Extentions in Add reference

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;
 }
 }

Writing/ Serialize  JSON Object

Let build accounts. Classt objects are similar to Dictionaries. Since we need to store more than single account , require arrays of object.

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());
 }
 }

The initializeJson method simply writes the objects as JSON string to a json file. So writing is done.

Reading the JSON Object

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
 {

}

We just put the JSON string to a ListView to demonstrate the reading operation.

The source code is available @ my Git Lab

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.