百度接口api:https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={date}&resource_id=6018 --date为查询的日期(如:2019-9)
接口返回的部分参数类:
public class Calendar { public int status { get; set; } public List<CalendarData> data { get; set; } } public class CalendarData { //public Holiday holiday { get; set; } public List<Holiday> holiday { get; set; } } public class Holiday { public string desc { get; set; } public string festival { get; set; } public List<HolidayList> list { get; set; } public string name { get; set; } public string rest { get; set; } } public class HolidayList { public string date { get; set; } /// <summary> /// 1休息2上班 /// </summary> public int status { get; set; } public string remark { get { return status == 1 ? "休假" : "上班"; } } } public class Calendar2 { public int status { get; set; } public List<CalendarData2> data { get; set; } } public class CalendarData2 { public Holiday holiday { get; set; } }
获取节假日
private static void GetHoliday(string date) { WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; var url = $"https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={date}&resource_id=6018"; var jsondata = client.DownloadString(url); try { var model = JsonConvert.DeserializeObject<Calendar>(jsondata); foreach (var item in model.data) { foreach (var holiday in item.holiday) { foreach (var day in holiday.list) { Console.WriteLine($"日期:{day.date},{day.remark}"); } } } } catch (Exception) { var model = JsonConvert.DeserializeObject<Calendar2>(jsondata); foreach (var item in model.data) { if (item.holiday != null && item.holiday.list != null) { foreach (var day in item.holiday.list) { Console.WriteLine($"日期:{day.date},{day.remark}"); } } } } //JObject jobject = JObject.Parse(json); //var holiday = jobject["data"][0]["holiday"]; //if (holiday != null && holiday.Children().Count() > 0) //{ // foreach (dynamic item in holiday.Children().ToList()) // { // foreach (dynamic day in item.list) // { // string remark = day.status == 1 ? "休假" : "上班"; // Console.WriteLine($"日期:{day.date},{remark}"); // } // } //} }
注意: 接口返回的参数中有些 holiday 不一定全是集合
demo代码下载地址:demo