[{"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 获取起始项值?
给定以下具体类:
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));
使用 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
似乎您想将 json 字符串反序列化为 C# class
.
JavaScriptSerializer jss= new JavaScriptSerializer();
CustomClass tempClass = jss.Deserialize<CustomClass>(jsonString);
jsonString
是您在问题中提到的json
数据。然后,可以在类上使用 linq。