Newtonsoft.Json过滤输出

时间:2019-04-23 19:11:23

标签: c# .net json.net

在过去的24小时(Console.WriteLine(statusCollection...日期已格式化)中,如果s.Service_name等于“ cloud_networking” ,我将如何过滤输出(s.Begin)以仅显示结果像这样2018-05-19T04:39:59Z

class Program
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    //public static void Main()
    public static void Main(string[] args)
    {
        using (var webClient = new WebClient())
        {

            String rawJSON = webClient.DownloadString("https://status.cloud.google.com/incidents.json");
            List<Status> statusCollection = JsonConvert.DeserializeObject<List<Status>>(rawJSON);
            Console.WriteLine(statusCollection.Count + "Last Run:" + DateTime.Now.ToString("MM/dd/yyyy h:mm tt"));
            //Console.WriteLine(statusCollection.Count + " items");

            Console.WriteLine(string.Join("\n", statusCollection.Select(s => string.Format("{0} {1} ({2}) {3} - {4} - {5} updates",
                                                   s.Begin, s.Number, s.Severity, s.Service_name, s.External_desc, s.Updates.Count))));
            log.Info(DateTime.Now.ToString("\n MM/dd/yyyy h:mm tt"));
        }
    }
}

public class Status
{
    public string Begin { get; set; }
    public string Created { get; set; }
    public string End { get; set; }
    public string External_desc { get; set; }
    public string Modified { get; set; }
    [JsonProperty("most-recent-update")]
    public MRUpdateContainer Most_recent_update { get; set; }
    public int Number { get; set; }
    public bool Public { get; set; }
    public string Service_key { get; set; }
    public string Service_name { get; set; }
    public string Severity { get; set; }
    public List<Update> Updates { get; set; }
    public string Uri { get; set; }
}

public class MRUpdateContainer
{
    public string Created { get; set; }
    public string Modified { get; set; }
    public string Text { get; set; }
    public string When { get; set; }
}
public class Update
{
    public string Created { get; set; }
    public string Modified { get; set; }
    public string Text { get; set; }
    public string When { get; set; }
}

1 个答案:

答案 0 :(得分:1)

(1)您可以将Begin属性类型更改为DateTime,以便更轻松地基于它进行过滤。 Json.Net can deserialize ISO 8601的日期是DateTime:

public DateTime Begin { get; set; }

(2)反序列化收集后,可以使用Linq .Where-操作过滤数据,如下所示:

DateTime start = DateTime.Now.AddHours(-24);
statusCollection = statusCollection.Where(r => r.Service_name == "cloud_networking" && r.Begin > start).ToList();