c# - Linq 查询 JObject

标签 c# json linq asp.net-mvc-4 json.net

我正在使用 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/

相关文章:

c# - 什么是最先进的自动更新技术?

ios - RestKit JSON 空值崩溃

c# - 方法上的 Webapi 参数为空

c# - sql linq之间有什么区别吗

c# - 为 Dictionary<string,List<string>> 中的多个 KeyValuePairs 计算 List<T> 中的项目总数

c# - 运行时的where条件

c# - 将选项卡控件的 SelectedItem 与 MVVM 绑定(bind)是个好主意吗?

javascript - 如何获取失败的ajax错误消息

c# - 多个 JOINS 之间有条件 : LINQ query

c# - 如何在不将文件保存到服务器的情况下从文件输入中读取 excel 文件