问题
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?
回答1:
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());
}
回答2:
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.
来源:https://stackoverflow.com/questions/22648030/how-can-i-read-json-from-a-file-stored-locally