开发者

Read JSON (text file) into .NET application

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 howev开发者_StackOverflow社区er 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.


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


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


Alternatively, you can have a look at the JSONReaderWriterFactory from the .Net 3.5SP1 stack.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜