2017-08-22 77 views
0

我在我的應用程序有這個launchSettings.json:獲取從JSON值與LINQ

{ 
    "iisSettings": { 
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": { 
     "applicationUrl": "http://localhost:5000/", 
     "sslPort": 0 
    } 
    }, 
    "profiles": { 
    "ProfileA": { 
     "commandName": "Project", 
     "commandLineArgs": "-c", 
     "launchBrowser": false, 
     "launchUrl": "http://ayda.eastus.cloudapp.azure.com/api", 
     "environmentVariables": { 
     "variableA" : "valueA", 
     "variableB" : "valueB" 
     } 
    }, 
    "ProfileB": { 
     "commandName": "Project", 
     "commandLineArgs": "-c", 
     "launchBrowser": false, 
     "launchUrl": "http://localhost:5000/api/values", 
     "environmentVariables": { 
     "variable1" : "value1", 
     "variable2" : "value2" 
     } 
    } 
    } 
} 

我需要從「概貌」「environmentVariables」一節得到的所有值。爲此,我寫了一些代碼,使用json.net:

using (var file = File.OpenText("Properties\\launchSettings.json")) 
{ 
    var reader = new JsonTextReader(file); 
    var jObject = JObject.Load(reader); 

    var variables = jObject.GetValue("profiles")["profileB"]["environmentVariables"].Children<JProperty>().ToList(); //how to do this in linq 
    foreach (var variable in variables) 
    { 
     Console.WriteLine(variable.Name + " " + variable.Value.ToString()); 
    } 
} 

它輸出

variable1 : value1 
variable2 : value2 

它不正是我想要的,但如何做同樣的事情LINQ?

,我發現這個方法,但它返回從該文件的所有 「environmentVariables」 段值:

var variables = jObject 
        .GetValue("profiles") 
        .SelectMany(profiles => profiles.Children()) 
        .SelectMany(profile => profile.Children<JProperty>()) 
        .Where(prop => prop.Name == "environmentVariables") 
        .SelectMany(prop => prop.Value.Children<JProperty>()) 
        .ToList(); 

它輸出

variableA : valueA 
variableB : valueB 
variable1 : value1 
variable2 : value2 

回答

0

你可以試試這個?

var variables = jObject.GetValue("profiles")["ProfileB"].Last 
          .SelectMany(profile => profile.Children<JProperty>()) 
          .ToList(); 
+0

謝謝ansver,它的工作。但如何使這部分'[「ProfileB」]。最後'linq也。也許'選擇'和'Where'組合什麼的? – Yaros