【发布时间】:2022-01-06 21:33:31
【问题描述】:
我需要从 json 文件中获取数据,该文件位于我的计算机中,我将代码粘贴在下面但出现错误:
Newtonsoft.Json.JsonReaderException: '解析值时遇到意外字符:h.路径'',第 0 行,位置 0。'
谁能给我一个解决方案?在此先感谢:)
模型类jsondata.cs
namespace fetch_data_jsonfile.Models
{
public class jsondata
{
public string id { get; set; }
public string title { get; set; }
public string price { get; set; }
public string description { get; set; }
public string category { get; set; }
public string image { get; set; }
}
public class Products
{
public IList<jsondata> products;
}
}
控制器:
namespace fetch_data_jsonfile.Controllers
{
public class JsonfileController : Controller
{
[HttpGet]
public ActionResult Home()
{
// Example JSON
var json = "D:/Newfolder/products.json";
var Products = JsonConvert.DeserializeObject<Products>(json);
return View(Products);
}
}
}
查看:Home.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>json</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<ul>
@foreach (var jsondata in Model.Products)
{
<li>@jsondata.title</li>
}
</ul>
</div>
</div>
</body>
</html>
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文件长什么样?似乎 JSON 解析器认为文件中存在格式错误。
-
我添加了json文件数据..
-
我刚刚意识到您传递的是 json 文件的路径,而不是 json 本身。 JsonConvert.DeserializeObject 函数接受 json 内容的字符串。根据 json 的大小,您可以使用例如读取整个文件。 File.ReadAllText 或者如果它是一个较大的文件,我认为您也许可以将 TextReader 传递给 DeserializeObject 函数。
-
能否请您给出答案,因为我是初学者,我不知道如何阅读 json 文件 :(
-
this 如果文件不是数百兆字节,可能会有帮助:)
标签: c# .net asp.net-mvc razor