Linq query JObject

后端 未结 4 1098
日久生厌
日久生厌 2021-01-19 01:15

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

 \"RegistrationList\": [
    {
      \"CaseNumber\": \"120654-1330\",
           


        
相关标签:
4条回答
  • 2021-01-19 02:06

    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>
    
    0 讨论(0)
  • 2021-01-19 02:09

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-19 02:09

    I think you want to get the JSON string like below:

    {
    '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': ''
                                        }
                                    },
                                ]
    }
    

    If so, you can get below code working for your question:

                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);
            }
    
    0 讨论(0)
  • 2021-01-19 02:16
    
    
        var serializer = new JavaScriptSerializer();
        object modelData = serializer.DeserializeObject(jsonstring);
    
    
    0 讨论(0)
提交回复
热议问题