天気予報APIから情報を取得する

2023年2月13日

練習用コードのため、実用性は低いですので悪しからず

リアル天気予報APIの取得

情報ページ(フリーです。ただし、サーバの永久維持保証はありません)

基本検証コード

NewtonソフトのJsonコンバータを採用しているコードからSystem.Text.Jsonへの更新作業手順概要をベースにしてます

//using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Windows.Forms;

namespace WeatherChecker
{
    public Form1()
    {
        InitializeComponent();

        // 都市名と都市コードの辞書を初期化
        cityNames = new Dictionary<string, string>
        {
            { "東京都", "400040" },
            { "大阪府", "1" },
            { "愛知県", "2" },
            { "福岡県", "10" }
        };

        // 都市名をComboBoxに追加
        foreach (KeyValuePair<string, string> data in cityNames)
        {
            areaBox.Items.Add(data.Key);
        }
    }

    // 都市名が選択されたときの処理
    private void CitySelected(object sender, EventArgs e)
    {
        // 天気情報サービスにアクセス
        string cityCode = cityNames[areaBox.Text];
        string url = $"https://weather.tsukumijima.net/api/forecast/city/{cityCode}";

        HttpClient client = new HttpClient();
        string result = client.GetStringAsync(url).Result;

        // 天気情報からアイコンのURLを取り出す
        WeatherInfo weatherInfo = JsonSerializer.Deserialize<WeatherInfo>(result);
        var data = weatherInfo.description.bodyText;
        textBox1.Text = data;
    }

    // 終了メニューがクリックされたときの処理
    private void ExitMenuClicked(object sender, EventArgs e)
    {
        // フォームを閉じる
        this.Close();
    }

        public class WeatherInfo
        {
            public DateTime publicTime { get; set; }
            public string publicTimeFormatted { get; set; }
            public string publishingOffice { get; set; }
            public string title { get; set; }
            public string link { get; set; }
            public Description description { get; set; }
            public Forecast[] forecasts { get; set; }
            public Location location { get; set; }
            public Copyright copyright { get; set; }
        }

        public class Description
        {
            public DateTime publicTime { get; set; }
            public string publicTimeFormatted { get; set; }
            public string headlineText { get; set; }
            public string bodyText { get; set; }
            public string text { get; set; }
        }

        public class Location
        {
            public string area { get; set; }
            public string prefecture { get; set; }
            public string district { get; set; }
            public string city { get; set; }
        }

        public class Copyright
        {
            public string title { get; set; }
            public string link { get; set; }
            public Image image { get; set; }
            public Provider[] provider { get; set; }
        }

        public class Image
        {
            public string title { get; set; }
            public string link { get; set; }
            public string url { get; set; }
            public int width { get; set; }
            public int height { get; set; }
        }

        public class Provider
        {
            public string link { get; set; }
            public string name { get; set; }
            public string note { get; set; }
        }

        public class Forecast
        {
            public string date { get; set; }
            public string dateLabel { get; set; }
            public string telop { get; set; }
            public Detail detail { get; set; }
            public Temperature temperature { get; set; }
            public Chanceofrain chanceOfRain { get; set; }
            public Image1 image { get; set; }
        }

        public class Detail
        {
            public string weather { get; set; }
            public string wind { get; set; }
            public string wave { get; set; }
        }

        public class Temperature
        {
            public Min min { get; set; }
            public Max max { get; set; }
        }

        public class Min
        {
            public string celsius { get; set; }
            public string fahrenheit { get; set; }
        }

        public class Max
        {
            public string celsius { get; set; }
            public string fahrenheit { get; set; }
        }

        public class Chanceofrain
        {
            public string T00_06 { get; set; }
            public string T06_12 { get; set; }
            public string T12_18 { get; set; }
            public string T18_24 { get; set; }
        }

        public class Image1
        {
            public string title { get; set; }
            public string url { get; set; }
            public int width { get; set; }
            public int height { get; set; }
        }
    }
}

例外処理、ファイルクローズ処理を配慮した検証コード

//using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows.Forms;
//using Newtonsoft.Json;

namespace WeatherChecker
{
    public partial class Form1 : Form
    {
        private Dictionary<string, string> cityNames;

        public Form1()
        {
            InitializeComponent();

            cityNames = new Dictionary<string, string>
            {
                { "東京都", "400040" },
                { "大阪府", "1" },
                { "愛知県", "2" },
                { "福岡県", "10" }
            };

            foreach (KeyValuePair<string, string> data in cityNames)
            {
                areaBox.Items.Add(data.Key);
            }
        }

        private async void CitySelected(object sender, EventArgs e)
        {
            try
            {
                // 天気情報サービスにアクセスする
                string cityCode = cityNames[areaBox.Text];
                string url = $"https://weather.tsukumijima.net/api/forecast/city/{cityCode}";

                using (HttpClient client = new HttpClient())
                {
                    string result = await client.GetStringAsync(url);

                    // 天気情報からアイコンのURLを取り出す
                    WeatherInfo weatherInfo = JsonSerializer.Deserialize<WeatherInfo>(result);
                    var data = weatherInfo.description.bodyText;
                    textBox1.Text = data;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ExitMenuClicked(object sender, EventArgs e)
        {
            // フォームを閉じる
            this.Close();
        }

        public class WeatherInfo
        {
            public DateTime publicTime { get; set; }
            public string publicTimeFormatted { get; set; }
            public string publishingOffice { get; set; }
            public string title { get; set; }
            public string link { get; set; }
            public Description description { get; set; }
            public Forecast[] forecasts { get; set; }
            public Location location { get; set; }
            public Copyright copyright { get; set; }
        }

        public class Description
        {
            public DateTime publicTime { get; set; }
            public string publicTimeFormatted { get; set; }
            public string headlineText { get; set; }
            public string bodyText { get; set; }
            public string text { get; set; }
        }

        public class Location
        {
            public string area { get; set; }
            public string prefecture { get; set; }
            public string district { get; set; }
            public string city { get; set; }
        }

        public class Copyright
        {
            public string title { get; set; }
            public string link { get; set; }
            public Image image { get; set; }
            public Provider[] provider { get; set; }
        }

        public class Image
        {
            public string title { get; set; }
            public string link { get; set; }
            public string url { get; set; }
            public int width { get; set; }
            public int height { get; set; }
        }

        public class Provider
        {
            public string link { get; set; }
            public string name { get; set; }
            public string note { get; set; }
        }

        public class Forecast
        {
            public string date { get; set; }
            public string dateLabel { get; set; }
            public string telop { get; set; }
            public Detail detail { get; set; }
            public Temperature temperature { get; set; }
            public Chanceofrain chanceOfRain { get; set; }
            public Image1 image { get; set; }
        }

        public class Detail
        {
            public string weather { get; set; }
            public string wind { get; set; }
            public string wave { get; set; }
        }

        public class Temperature
        {
            public Min min { get; set; }
            public Max max { get; set; }
        }

        public class Min
        {
            public string celsius { get; set; }
            public string fahrenheit { get; set; }
        }

        public class Max
        {
            public string celsius { get; set; }
            public string fahrenheit { get; set; }
        }

        public class Chanceofrain
        {
            public string T00_06 { get; set; }
            public string T06_12 { get; set; }
            public string T12_18 { get; set; }
            public string T18_24 { get; set; }
        }

        public class Image1
        {
            public string title { get; set; }
            public string url { get; set; }
            public int width { get; set; }
            public int height { get; set; }
        }
    }
}