Linq查询JObject [英] Linq query JObject

查看:355
本文介绍了Linq查询JObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Json.net进行序列化,然后制作一个看起来像这样的JObject:

I am using Json.net for serializing and then making an JObject that looks like this:

 "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表/视图中. 我只想显示CaseNumber,FirstName和Comment.

How do i query this into a new Object or list, that is easily put into some html table/view. I only want to display the CaseNumber, FirstName and Comment.

推荐答案

我只想显示CaseNumber,FirstName和Comment.

I only want to display the CaseNumber, FirstName and Comment.

与在ASP.NET MVC中一样,您可以从编写符合您要求的视图模型开始:

As always in ASP.NET MVC you could start by writing a view model that matches your requirements:

public class MyViewModel
{
    public string CaseNumber { get; set; }
    public string FirstName { get; set; }
    public string Comment { get; set; }
}

然后在控制器操作中,从已经拥有的JObject实例构建视图模型:

then in your controller action you build the view model from the JObject instance you already have:

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);
}

最后在强类型视图中显示所需的信息:

and finally in your strongly typed view you display the desired information:

@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>

这篇关于Linq查询JObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆