我有一个远程 URL,从那里我读取了一个如下所示的 JSON 对象:
{"books":
[
{"title":"Book 1", "author":"Author1", "price":762, "inStock":15},
{"title":"Book 2", "author":"Author2", "price":100, "inStock":1},
{"title":"Book 3", "author":"Author3", "price":185.5, "inStock":5},
{"title":"Book 4", "author":"Author 4", "price":1748, "inStock":3},
{"title":"Book 5", "author":"Author 5", "price":999, "inStock":20},
{"title":"Book 6", "author":"Author 6", "price":499.5, "inStock":3},
{"title":"Book 7", "author":"Author 7", "price":564.5, "inStock":0}
]
}
我创建了两个类 Book.cs
public class Book
{
public string title;
public string author;
public string price;
public string inStock;
}
和 Books.cs
public class Books
{
public IList<Book> books { get; set; }
}
如何正确解析 JSON 以便我可以在 Razor HTML 中显示内容
这是我的 Controller :
public ActionResult Index()
{
var webClient = new WebClient();
var json = webClient.DownloadString(@"http://www.myurl.json");
Books[] books = JsonConvert.DeserializeObject<Books[]>(json);
return View(books);
}
最佳答案
您的 Books
类已经包含一个集合属性来表示您的每一本书,因此您不需要实际反序列化一个 Books[]
而只是一个书籍
对象:
// Since Books is already a container element, it will map the "books" property
// from your JSON object to the matching IList<Book> property
var books = JsonConvert.DeserializeObject<Books>(json);
示例
您可以 see a complete working example of this here以及下面代码片段中演示的示例代码。
// YourClasses.cs
namespace Example
{
public class Book
{
public string title;
public string author;
public string price;
public string inStock;
}
public class Books
{
public IList<Book> books;
}
}
// YourController.cs
namespace Example
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
// Example JSON in lieu of API call
var json = "{\"books\":[{\"title\":\"Book 1\", \"author\":\"Author1\", \"price\":762, \"inStock\":15},{\"title\":\"Book 2\", \"author\":\"Author2\", \"price\":100, \"inStock\":1},{\"title\":\"Book 3\", \"author\":\"Author3\", \"price\":185.5, \"inStock\":5},{\"title\":\"Book 4\", \"author\":\"Author 4\", \"price\":1748, \"inStock\":3},{\"title\":\"Book 5\", \"author\":\"Author 5\", \"price\":999, \"inStock\":20},{\"title\":\"Book 6\", \"author\":\"Author 6\", \"price\":499.5, \"inStock\":3},{\"title\":\"Book 7\", \"author\":\"Author 7\", \"price\":564.5, \"inStock\":0}]}";
var books = JsonConvert.DeserializeObject<Books>(json);
return View(books);
}
}
}
// Index.cshtml
@model Example.Books
<ul>
@foreach(var book in Model.books){
<li>@book.title</li>
}
</ul>
关于c# - 在ASP.NET MVC中解析JSON文件并在网页中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42259970/