Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read JSON (text file) into .NET application

Tags:

json

c#

I have a configuration file in the following JSON format:

{

  "key1": "value1",  
  "key2": "value2",  
  "key3": false,  
  "key4": 10,  

}

The user can set/unset the configuration values using a text editor. I however need to read it in my C# application. Whats the best way to do so for JSON? The above keys are not associated with a class.

like image 734
Bi. Avatar asked Apr 14 '10 19:04

Bi.


2 Answers

Take a look at Json.NET: http://json.codeplex.com

like image 137
ccellar Avatar answered Nov 06 '22 13:11

ccellar


Would this work for you?

        System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
        string json = @"{
                          'key1': 'value1',  
                          'key2': 'value2',  
                          'key3': false,  
                          'key4': 10
                        }";
        Dictionary<string, string> dic = js.Deserialize<Dictionary<string, string>>(json); // deserialize

        foreach (KeyValuePair<string,string> o in dic)
        {
            // do whatever
        }


        dic.Add("newKey", "new value"); // add an attribute

        string newjson = js.Serialize(dic);  // serialize back to string
like image 20
Kenneth J Avatar answered Nov 06 '22 14:11

Kenneth J