如何从本地存储的文件中读取JSON?

dre*_*att 10 c# asp.net asp.net-mvc json.net asp.net-mvc-4

我试图使用JSON.Net加载本地存储在ASP.Net MVC 4站点上的JSON文件,但是我无法指向该文件.这是我想要做的:

List<Treatment> treatments = JsonConvert.DeserializeObject<List<Treatment>>(Server.MapPath("~/Content/treatments.json"));
Run Code Online (Sandbox Code Playgroud)

并且我遇到了这个错误:

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.
Run Code Online (Sandbox Code Playgroud)

我应该做些什么呢?

小智 27

您需要首先使用a读取JSON FileStream.

试试这个.

using(StreamReader sr = new StreamReader(Server.MapPath("~/Content/treatments.json")))
{
      treatments = JsonConvert.DeserializeObject<List<Treatment>>(sr.ReadToEnd());
}
Run Code Online (Sandbox Code Playgroud)


Sam*_*Axe 9

您将路径和文件名作为JSON有效负载传递.您需要打开文件(例如FileStream)并将内容读入变量(例如StreamReader),并将文件内容作为有效负载传递给解串器.