-2

I have created JSON using following code.

List<int> _data = new List<int>();
        foreach (DataRow row in dt.Rows)
        {
            _data.Add((int)row["Id"]);
        }
        JavaScriptSerializer jss = new JavaScriptSerializer();
        chartData = jss.Serialize(_data);

Now can anyone tell me how do I save this is something like data.json? I want to write it into a file.

SPandya
  • 1,161
  • 4
  • 26
  • 63

1 Answers1

3

The Serialize method returns a String, doesn't it? So you can just use File.WriteAllText().

fero
  • 6,050
  • 1
  • 33
  • 56
  • it executed but not finding the file. I want to use it in the javascript – SPandya Dec 04 '13 at 10:10
  • @Saumil what have executed? – vmeln Dec 04 '13 at 10:13
  • I'm not sure what you mean. Can you give a little more context? _Who_ doesn't find the file? And where does the JS come from you want to use the JSON in? – fero Dec 04 '13 at 10:14
  • I wrote `File.WriteAllText("data.json",chartData);` the code executed without any error but not getting the file. – SPandya Dec 04 '13 at 10:15
  • The file will be placed in the current working directory, most likely in your `bin\Debug` or `bin\Release` folder where the current `.exe` file is located (if it's a "Windows executable" project). You may want to specify a full path instead of just `"data.json"`. – fero Dec 04 '13 at 10:17
  • It is an aspx page and I am performing this in .cs file. I want to call this .json extension file using Ajax and use the datafrom the file for displying it on highchart. – SPandya Dec 04 '13 at 10:19
  • Then you don't have to save the file to hard disk (that makes no sense). It has to be created on-the-fly within the web request because the `aspx` which is called from HighChart must contain the JSON data. So the `aspx` file must return the JSON string, and no HTML or anything else. Nothing needs to be saved to a file. – fero Dec 04 '13 at 10:24
  • Well I tried that way I called the aspx page but I am not getting success in it. – SPandya Dec 04 '13 at 10:25
  • The function on success of Ajax call is not executing – SPandya Dec 04 '13 at 10:26
  • OK, but this isn't related to your original question anymore. Maybe you should ask a question on how to perform an AJAX call with JSON result in an ASP.NET project - because you already _have_ the JSON that must be returned (it's the `chartData` string). – fero Dec 04 '13 at 10:28
  • May be this question is suitable for you: http://stackoverflow.com/questions/5756147/basic-simple-asp-net-jquery-json-example – fero Dec 04 '13 at 10:30