Click here to Skip to main content
15,847,077 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All,
I don't have any idea how to read and write Json file in c#, but in my project client requirment is to implement Json, so please help me if any body have any URL or sample code where it is given the detail steps for using Json in asp.net(C#).

Details like Insert/update/delete data from Json file.

Thanking you in advance.
Posted
Updated 10-Oct-12 3:07am
v2

Json are simmilar to XML in terms of use but they are equivalent to txt file in terms of accessibility. you can use teh following code to read/write a jasoin file. you need to change the code as per your requirement.

READ :

C#
//Open the file              
var stream = File.OpenText("json file.txt"); 
//Read the file              
string st = stream.ReadToEnd();                           
var jsonArray = JsonArray.Parse(st);              
foreach (var item in jsonArray)              
{                                   
JsonObject ob = new JsonObject(item);                   
foreach (var t in ob.Values)                  
{                       
JsonObject oo = new JsonObject(t);                       
foreach (var x in oo)                      
{                          
textBox1.AppendText(x.Key + " : " + x.Value + "\n");                      
}                  
}                 


WRITE :

C#
KeyValuePair<string, JsonValue> pair = new KeyValuePair<string, JsonValue>("FName","Sourabh");             
KeyValuePair<string, JsonValue> pair2 = new KeyValuePair<string, JsonValue>("LName", "SInha");              
List<KeyValuePair<string, JsonValue>> list = new List<KeyValuePair<string, JsonValue>>();             
list.Add(pair);             
list.Add(pair2);                          
JsonObject jObject = new JsonObject(list);             
var stream = new StreamWriter("json out file.txt");             
            
foreach (var x in jObject)             
{               
//  textBox1.AppendText(x.Key + " : " + x.Value + "\n");                 
textBox1.AppendText(x.ToString() + "\n");                 
stream.WriteLine(x.ToString() + "\n");             
}             
JsonArray jarray = new JsonArray("item1","item2","Item3");             
foreach (var x in jarray)             
{                                 
textBox1.AppendText(x.ToString());                 
stream.WriteLine(x.ToString());             
}         
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900