Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read JSON from a file stored locally?

I am attempting to use JSON.Net to load in a JSON file stored locally on an ASP.Net MVC 4 site, but am having trouble pointing to the file. Here is what I am trying to do:

List<Treatment> treatments = JsonConvert.DeserializeObject<List<Treatment>>(Server.MapPath("~/Content/treatments.json"));

and am hitting this error:

An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll but was not handled in user code

Additional information: Unexpected character encountered while parsing value: c. Path '', line 0, position 0.

What should I be doing differently?

like image 822
drewwyatt Avatar asked Mar 25 '14 22:03

drewwyatt


People also ask

How do I use local JSON fetch?

Select the path to the JSON file as a variable named url. Add an event listener to the button click , making a fetch request to the url. Once a response is received from the JSON file, return it as JSON into a JavaScript object with json()

How do I open local JSON in Chrome?

@UmeshPatil In Chrome you should just right click by mouse and choose "Open in new tab" at the method which returns JSON data from "Network" -> "XHR" tab of Chrome browser.


2 Answers

You need to read in the JSON first using a FileStream.

Try this.

using(StreamReader sr = new StreamReader(Server.MapPath("~/Content/treatments.json")))
{
      treatments = JsonConvert.DeserializeObject<List<Treatment>>(sr.ReadToEnd());
}
like image 128
SlightlyMoist Avatar answered Oct 02 '22 00:10

SlightlyMoist


You are passing in the path and filename as your JSON payload. You need to open the file (eg. FileStream) and read the contents into a variable (eg. StreamReader) and pass the file contents as the payload to the deserializer.

like image 39
Sam Axe Avatar answered Oct 01 '22 22:10

Sam Axe