Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a .json file into c# program

Tags:

json

c#

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.

like image 301
ford prefect Avatar asked Aug 30 '13 17:08

ford prefect


People also ask

Can C parse JSON?

jsmn (pronounced like 'jasmine') is a minimalistic JSON parser in C. It can be easily integrated into the resource-limited projects or embedded systems. You can find more information about JSON format at json.org.

What is JSON object in C?

JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. JSON stands for JavaScript Object Notation. The format was specified by Douglas Crockford.


2 Answers

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); } 
like image 140
STW Avatar answered Sep 19 '22 07:09

STW


Another good way to serialize json into c# is below:

RootObject ro = new RootObject();      try     {          StreamReader sr = new StreamReader(FileLoc);         string jsonString = sr.ReadToEnd();         JavaScriptSerializer ser = new JavaScriptSerializer();         ro = ser.Deserialize<RootObject>(jsonString);      } 

you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client

like image 34
ford prefect Avatar answered Sep 21 '22 07:09

ford prefect