ASP.NET MVC读取本地JSON文件报Newtonsoft.Json解析错误求解决方案
错误原因
你遇到的Newtonsoft.Json.JsonReaderException报错核心原因是:JsonConvert.DeserializeObject<T>方法的入参要求是JSON格式的字符串内容,但你直接传入了本地文件的路径字符串D:/Newfolder/products.json,Newtonsoft.Json会尝试把路径字符串当作JSON内容解析,自然会因为不符合JSON格式抛出异常。
修复方案
- 第一步:修正模型类定义
你当前定义的Products类中的products是字段而非属性,Newtonsoft.Json默认只会序列化/反序列化公共属性,需要补充get/set访问器,同时可以根据JSON字段类型调整属性类型避免隐式转换问题:
namespace fetch_data_jsonfile.Models { public class jsondata { public int id { get; set; } public string title { get; set; } public decimal price { get; set; } public string description { get; set; } public string category { get; set; } public string image { get; set; } // 若需要读取评分信息可补充下面的属性,不需要可以省略 // public Rating rating { get; set; } } // 不需要读取评分信息可以删掉这个类 public class Rating { public decimal rate { get; set; } public int count { get; set; } } public class Products { // 补充get/set访问器,改为属性定义 public IList<jsondata> products { get; set; } } }
- 第二步:修正控制器逻辑,先读取JSON文件内容再反序列化
你需要先通过文件读取API拿到JSON文件的文本内容,再传给反序列化方法。另外推荐使用相对路径读取文件,避免部署到服务器后绝对路径失效,你可以把products.json放到项目根目录下的App_Data文件夹(专门放应用数据的目录,默认不会被外界直接访问),再通过Server.MapPath映射物理路径:
// 需先引用System.IO命名空间用于文件读取 using System.IO; using Newtonsoft.Json; using fetch_data_jsonfile.Models; namespace fetch_data_jsonfile.Controllers { public class JsonfileController : Controller { [HttpGet] public ActionResult Home() { // 若你坚持用绝对路径,直接把这里替换成你原来的路径字符串即可 string filePath = Server.MapPath("~/App_Data/products.json"); // 读取JSON文件的全部文本内容 string jsonContent = File.ReadAllText(filePath); // 反序列化JSON内容为实体对象 var products = JsonConvert.DeserializeObject<Products>(jsonContent); return View(products); } } }
- 第三步:修正JSON格式问题
你提供的JSON文件末尾数组最后一个元素后有多余的逗号,部分JSON解析器会因此报错,建议删除多余逗号:
{ "products" : [{ "id":1, "title":"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops", "price":109.95, "description":"Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday", "category":"men's clothing", "image":"https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg", "rating":{"rate":3.9,"count":120} }]}
- 第四步:权限校验
确保你的JSON文件的读取权限正常,ASP.NET运行时的账户对文件所在目录有可读权限。
修复上述问题后,原视图代码无需改动即可正常遍历输出商品标题。
内容的提问来源于stack exchange,提问作者Tony S
相关产品推荐
相关产品推荐

