我正在使用 Json.net 进行序列化,然后制作一个如下所示的 JObject:
"RegistrationList": [
{
"CaseNumber": "120654-1330",
"Priority": 5,
"PersonId": 7,
"Person": {
"FirstName": "",
"LastName": "",
},
"UserId": 7,
"User": {
"Id": 7,
"CreatedTime": "2013-07-05T13:09:57.87",
"Comment": "",
},
我如何将其查询到新对象或列表中,以便轻松放入某些 html 表/ View 中。 我只想显示 CaseNumber、FirstName 和 Comment。
最佳答案
I only want to display the CaseNumber, FirstName and Comment.
与往常一样,在 ASP.NET MVC 中,您可以从编写符合您要求的 View 模型开始:
public class MyViewModel
{
public string CaseNumber { get; set; }
public string FirstName { get; set; }
public string Comment { get; set; }
}
然后在您的 Controller 操作中,您从已有的 JObject 实例构建 View 模型:
public ActionResult Index()
{
JObject json = ... the JSON shown in your question (after fixing the errors because what is shown in your question is invalid JSON)
IEnumerable<MyViewModel> model =
from item in (JArray)json["RegistrationList"]
select new MyViewModel
{
CaseNumber = item["CaseNumber"].Value<string>(),
FirstName = item["Person"]["FirstName"].Value<string>(),
Comment = item["User"]["Comment"].Value<string>(),
};
return View(model);
}
最后在您的强类型 View 中显示所需的信息:
@model IEnumerable<MyViewModel>
<table>
<thead>
<tr>
<th>Case number</th>
<th>First name</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.CaseNumber</td>
<td>@item.FirstName</td>
<td>@item.Comment</td>
</tr>
}
</tbody>
</table>
关于c# - Linq 查询 JObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17781996/