如何使用Cricket API构建C#应用程序

时间:2016-05-10 19:08:34

标签: c# api

我是C#编程的初学者。据我所知,我理解OOP的概念。我有一个建立一个类似于CricBuzz网站的桌面应用程序的任务,即我应该显示现场时间表和正在进行的板球比赛的得分。

我听说有API可以帮我这么做。我在网上找到了API,但问题是,我不知道如何在我的C#程序中实现或使用API​​。请帮帮我。

TIA。 :)

1 个答案:

答案 0 :(得分:0)

使用json2csharp生成的实体。 使用JavaScriptSerializer反序列化json和一个简单的顺序WebClient调用来下载json。你可以改进它的质量和组织,尝试async,Newtonsoft.Json进行序列化等等。这只是一个快速而肮脏的方法。

using System.Collections.Generic;
using JsSerializer = System.Web.Script.Serialization.JavaScriptSerializer;
using System.Net;


//
// http://cricapi.com/api/cricket/
//
namespace CricApi.Cricket
{
   public class Provider
    {
        public string url { get; set; }
        public string source { get; set; }
        public string pubDate { get; set; }
    }

    public class Datum
    {
        public string title { get; set; }
        public string description { get; set; }
        public string unique_id { get; set; }
    }

    public class RootObject
    {
        public Provider provider { get; set; }
        public List<Datum> data { get; set; }
        public bool cache { get; set; }
    }
}

//
//http://cricapi.com/api/cricketScore?unique_id=946981
//http://cricapi.com/api/cricketScore?unique_id=946765
//
namespace CricApi.CricketScore
{
  public class Provider
  {
    public string pubDate { get; set; }
    public string source { get; set; }
    public string url { get; set; }
  }

  public class RootObject
  {
    public bool cache { get; set; }
    public string inningsRequirement { get; set; }
    public string team2 { get; set; }
    public string team1 { get; set; }
    public string score { get; set; }
    public Provider provider { get; set; }
  }
}
// 
// how to use this
//
namespace CricApi
{
  class Program
  {
    static void Main (string[] args)
    {

      WebClient client = new WebClient();

      // Download cricket info
      //  dynamic dyn = JsonConvert.DeserializeObject(res);
      string cricketJson = client.DownloadString("http://cricapi.com/api/cricket/");
      Cricket.RootObject cro = new JsSerializer().Deserialize<Cricket.RootObject>(cricketJson);

      // Download cricket score info
      foreach (var datum in cro.data)
      {
        string uri = "http://cricapi.com/api/cricketScore?unique_id=" + datum.unique_id;
        string cricketScoreJson = client.DownloadString(uri);
        CricketScore.RootObject csro = new JsSerializer().Deserialize<CricketScore.RootObject>(cricketScoreJson);
      }

    }
  }
}