Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query 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": "",
    },

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.

like image 860
stianboe Avatar asked Jul 22 '13 07:07

stianboe


2 Answers

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

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

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>
like image 175
Darin Dimitrov Avatar answered Sep 20 '22 05:09

Darin Dimitrov


Several ways:

1) According documentation 'Using LINQ for JSON' you can query JObject in LINQ way

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) Use custom helper extention method for querying by specified path like this:

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;
    }
}
like image 39
Dmitry Pavlov Avatar answered Sep 22 '22 05:09

Dmitry Pavlov