drewwyatt
drewwyatt

Reputation: 6027

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?

Upvotes: 12

Views: 36895

Answers (2)

SlightlyMoist
SlightlyMoist

Reputation: 882

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());
}

Upvotes: 33

Sam Axe
Sam Axe

Reputation: 33738

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.

Upvotes: 9

Related Questions