Skip to content

Instantly share code, notes, and snippets.

@chomado
Last active February 22, 2017 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chomado/68b060d63d2229376dfaae7277538ed9 to your computer and use it in GitHub Desktop.
Save chomado/68b060d63d2229376dfaae7277538ed9 to your computer and use it in GitHub Desktop.
class Program
{
static void Main(string[] args)
{
WeatherAsync().Wait();
Console.ReadKey(); // 何かキーを押すまでプログラムが終了しない
}
private static async Task WeatherAsync()
{
// 叩くAPIのエンドポイント。天気予報データがJSONで降ってくる
const string weatherApi = "http://weather.livedoor.com/forecast/webservice/json/v1?city=400040";
// .NET で HTTP を扱うには、HttpClient というクラスを使う
var client = new HttpClient();
// Webからデータを「非同期で」取ってくる
// (C# では、他の言語のような「コールバック」を使わず、await と書くことで、非同期処理の完了を待つことができる)
var response = await client.GetAsync(weatherApi);
// レスポンスから body のテキストを読み取る
var json = await response.Content.ReadAsStringAsync();
// 標準出力に表示。取得した生のJSONデータがコンソールに出力される
//Console.WriteLine(json);
// Json.NET で、JSON をデシリアライズします。
// ここで、C#の機能のひとつである dynamic という、型の無い動的なオブジェクトとして受け取ります
var result = JsonConvert.DeserializeObject<Rootobject>(json);
Console.WriteLine(result.description.text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment