Linq query JObject



我使用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": "",
    },

我如何将其查询到一个新的Object或列表中,该列表可以很容易地放入一些html表/视图中。我只想显示CaseNumber、FirstName和Comment。

我只想显示CaseNumber、FirstName和Comment。

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

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

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

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

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

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

几种方法:

1) 根据文档"使用LINQ for JSON",您可以通过LINQ方式查询JObject

JObject o = JObject.Parse(@"{
  'CPU': 'Intel',
  'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive

2) 使用SelectToken 查询JSON

3) 使用自定义助手扩展方法按指定路径进行查询,如下所示:

public static class JsonHelpers
{
    public static JToken QueryJson(this object jsonObject, params string[] jsonPath)
    {
        const string separator = " -> ";
        if (jsonObject == null)
            throw new Exception(string.Format("Can not perform JSON query '{0}' as the object is null.",
                string.Join(separator, jsonPath ?? new string[0])));
        var json = (jsonObject as JToken) ?? JObject.FromObject(jsonObject);
        var token = json;
        var currentPath = "";
        if (jsonPath != null)
            foreach (var level in jsonPath)
            {
                currentPath += level + separator;
                token = token[level];
                if (token == null) break;
            }
        if (token == null)
            throw new Exception(string.Format("Can not find path '{0}' in JSON object: {1}", currentPath, json));
        return token;
    }
}

我认为您想要获得如下JSON字符串:

{
'RegistrationList': [       
            {
                'CaseNumber': '120654-1330',
                                    'Priority': 5,
                                    'PersonId': 7,
                                    'Person': {
                                        'FirstName': '0',
                                        'LastName': '',
                                    },
                                    'UserId': 7,
                                    'User': {
                                        'Id': 7,
                                        'CreatedTime': '2013-07-05T13:09:57.87',
                                        'Comment': ''
                                    }
                                },
                                {
                                    'CaseNumber': '120654-1330',
                                    'Priority': 5,
                                    'PersonId': 7,
                                    'Person': {
                                        'FirstName': '0',
                                        'LastName': '',
                                    },
                                    'UserId': 7,
                                    'User': {
                                        'Id': 7,
                                        'CreatedTime': '2013-07-05T13:09:57.87',
                                        'Comment': ''
                                    }
                                },
                            ]
}

如果是这样的话,你可以得到下面的代码来解决你的问题:

            string json = @"{
                            'RegistrationList': [
                                {
                                    'CaseNumber': '120654-1330',
                                    'Priority': 5,
                                    'PersonId': 7,
                                    'Person': {
                                        'FirstName': '0',
                                        'LastName': '',
                                    },
                                    'UserId': 7,
                                    'User': {
                                        'Id': 7,
                                        'CreatedTime': '2013-07-05T13:09:57.87',
                                        'Comment': ''
                                    }
                                },
                                {
                                    'CaseNumber': '120654-1330',
                                    'Priority': 5,
                                    'PersonId': 7,
                                    'Person': {
                                        'FirstName': '0',
                                        'LastName': '',
                                    },
                                    'UserId': 7,
                                    'User': {
                                        'Id': 7,
                                        'CreatedTime': '2013-07-05T13:09:57.87',
                                        'Comment': ''
                                    }
                                },
                            ]
                        }";
        JObject o = JObject.Parse(json);
        JArray list = (JArray)o["RegistrationList"];
        List<Tuple<string, string, string>> rList = new List<Tuple<string, string, string>>();
        foreach (var r in list)
        {
            Tuple<string, string, string> temp = new Tuple<string, string, string>(r["CaseNumber"].Value<string>(), r["Person"]["FirstName"].Value<string>(), r["User"]["Comment"].Value<string>());
            rList.Add(temp);
            Console.WriteLine(temp);
        }
var serializer=新的JavaScriptSerializer();object modelData=序列化程序。反序列化对象(jsonstring);

相关内容

  • 没有找到相关文章

最新更新