This project has moved. For the latest updates, please go here.

read a json file from my vs2010 project

Apr 15, 2011 at 1:37 AM
Edited Apr 15, 2011 at 1:38 AM

Hello all.I have found this sample code in the documentation that it works fine

string json = @"[
    ""Name"": ""Product 1"",
    ""ExpiryDate"": ""\/Date(978048000000)\/"",
    ""Price"": 99.95,
    ""Sizes"": null
    ""Name"": ""Product 2"",
    ""ExpiryDate"": ""\/Date(1248998400000)\/"",
    ""Price"": 12.50,
    ""Sizes"": null
List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
// 2
Product p1 = products[0];
// Product 1

But my prob is that i want to retrieve my json data from a file not from a string.the file is named "file.json" and 
i have already add it to my solution project in vs2010.How can i "load" the file data to my List<T>?
Thanx in advance.
May 4, 2011 at 10:02 PM
Edited May 4, 2011 at 10:02 PM

If the text (JSON) file is already in your project you'll need:

using System.IO;

You need System.IO to work with files.

Then you'll probably want to copy file.json into the relevant folders, probably <project>\bin\Debug and <project>\bin\Release so that the it'll be in the program folder; although looking at what you're likely to have in that file it might be better to put it in a non-protected folder.

Anyway, best practices aside, assuming for now the file pretty static and therefore OK to put in the program folder, you'll need to set up the filepath so that your program knows where to access it from. For this I'd just assign a static variable; something like:

private static string sJSONFilepath = Path.Combine(Application.StartupPath, "file.json"); 

And finally - to create your object from your JSON:

List<Product> products = JsonConvert.DeserializeObject<List<Product>>(File.ReadAllText(sJSONFilepath));