Linq query JObject

后端 未结 4 1137
日久生厌
日久生厌 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: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 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;
        }
    }
    

提交回复
热议问题