2014-03-25 220 views
9

我正在尝试使用JSON.Net加载本地存储在ASP.Net MVC 4网站上的JSON文件,但无法指向该文件。这里是我想要做的事:如何从本地存储的文件中读取JSON?

List<Treatment> treatments = JsonConvert.DeserializeObject<List<Treatment>>(Server.MapPath("~/Content/treatments.json")); 

和我打这个错误:

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. 

,我应该怎么做不同?

+1

请发布JSON文件。 – Icarus

+0

看起来您的JSON可能无法正确格式化,或者它可能在错误的地方有单引号 – Jaypal

回答

25

您需要先阅读JSON,然后使用FileStream

试试这个。

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

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

相关问题