2017-08-22 78 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