Read and parse a Json File in C# Read and parse a Json File in C# json json

Read and parse a Json File in C#

How about making everything easier with Json.NET?

    public void LoadJson()    {        using (StreamReader r = new StreamReader("file.json"))        {            string json = r.ReadToEnd();            List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);        }    }    public class Item    {        public int millis;        public string stamp;        public DateTime datetime;        public string light;        public float temp;        public float vcc;    }

You can even get the values dynamically without declaring Item class.

    dynamic array = JsonConvert.DeserializeObject(json);    foreach(var item in array)    {        Console.WriteLine("{0} {1}", item.temp, item.vcc);    }

Doing this yourself is an awful idea. Use Json.NET. It has already solved the problem better than most programmers could if they were given months on end to work on it. As for your specific needs, parsing into arrays and such, check the documentation, particularly on JsonTextReader. Basically, Json.NET handles JSON arrays natively and will parse them into strings, ints, or whatever the type happens to be without prompting from you. Here is a direct link to the basic code usages for both the reader and the writer, so you can have that open in a spare window while you're learning to work with this.

This is for the best: Be lazy this time and use a library so you solve this common problem forever.

This can also be done in the following way:

JObject data = JObject.Parse(File.ReadAllText(MyFilePath));