How can I read JSON from a file stored locally?

三世轮回 提交于 2019-12-20 19:57:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!