Linq查询JObject

时间:2013-07-22 07:22:45

标签: 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表/视图中。 我只想显示CaseNumber,FirstName和Comment。

4 个答案:

答案 0 :(得分:5)

  

我只想显示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 :(得分:2)

有几种方法:

1)根据文件&#39; Using LINQ for JSON&#39;你可以用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)Querying JSON with SelectToken

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

答案 2 :(得分:0)

我想你想获得如下的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);
        }

答案 3 :(得分:-1)



    var serializer = new JavaScriptSerializer();
    object modelData = serializer.DeserializeObject(jsonstring);