[英]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. 我试图使用JSON.Net加载本地存储在ASP.Net MVC 4站点上的JSON文件,但是我无法指向该文件。 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? 我应该做些什么呢?
You need to read in the JSON first using a FileStream
. 您需要首先使用
FileStream
读取JSON。
Try this. 试试这个。
using(StreamReader sr = new StreamReader(Server.MapPath("~/Content/treatments.json")))
{
treatments = JsonConvert.DeserializeObject<List<Treatment>>(sr.ReadToEnd());
}
You are passing in the path and filename as your JSON payload. 您将路径和文件名作为JSON有效负载传递。 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. 您需要打开文件(例如
FileStream
)并将内容读入变量(例如StreamReader
)并将文件内容作为有效负载传递给解串器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.