如何获得"开始"使用C#linq查询的项值?

时间:2016-01-25 04:57:54

标签: c# json list json.net

[{"service":"xxx",
    "processes":
    [
        {
            "name":"tomcat",
            "command":{
                "start": "/server/tomcat01/bin/tomcat01.sh start",
                "stop": "/server/tomcat01/bin/tomcat01.sh stop",
                "restart": "/server/tomcat01/bin/tomcat01.sh restart",
            }       
        }
    ]
}]

如何使用c#linq获取起始项值?

3 个答案:

答案 0 :(得分:5)

鉴于以下具体课程:

public class Command
{
    public string start { get; set; }
    public string stop { get; set; }
    public string restart { get; set; }
}

public class Process
{
    public string name { get; set; }
    public Command command { get; set; }
}

public class Services
{
    public string service { get; set; }
    public List<Process> processes { get; set; }
}

您可以反序列化json并使用以下内容检索所有启动的列表:

var json = @"[{""service"":""xxx"", ""processes"": [{""name"":""tomcat"", ""command"":{""start"":""/server/tomcat01/bin/tomcat01.shstart"", ""stop"":""/server/tomcat01/bin/tomcat01.shstop"", ""restart"":""/server/tomcat01/bin/tomcat01.shrestart"", } } ] }]";
var deserialized = JsonConvert.DeserializeObject<List<Services>>(json);
var starts = deserialized.Select(x => x.processes.Select(p => p.command?.start));

答案 1 :(得分:3)

使用Json.Net LINQ-to-JSON API,您可以这样做:

string command = JToken.Parse(json)
    .SelectMany(jo => jo.SelectToken("processes"))
    .Select(jo => (string)jo.SelectToken("command.start"))
    .FirstOrDefault();

...给出你的JSON输入会返回/server/tomcat01/bin/tomcat01.sh start

小提琴:https://dotnetfiddle.net/Ft3q2C

答案 2 :(得分:0)

您似乎希望将json字符串反序列化为C# class

JavaScriptSerializer jss= new JavaScriptSerializer();
CustomClass tempClass = jss.Deserialize<CustomClass>(jsonString); 

jsonString是您在问题中提到的json数据。然后你可以在课堂上使用linq。