inquisitiveIdiot inquisitiveIdiot - 4 months ago 63
JSON Question

Loading a .json file into c# program

I am new to c# and json objects and I am trying to move my website from xml based config files to json based ones. Is there a way to load in a .json file in so that it turns into the object? I have been searching the web and I cannot find one. I already have the xml file converted and saved as a .json. I would rather not use a 3rd party library.

Thanks

STW STW
Answer

You really should use an established library, such as Newtonsoft.Json (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.

Here's a sample of reading JSON using Newtonsoft.Json:

JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));

// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
  JObject o2 = (JObject) JToken.ReadFrom(reader);
}
Comments