재우니의 블로그



http://blog.anthonybaker.me/2013/05/how-to-consume-json-rest-api-in-net.html

https://github.com/anthonybaker/JsonAPIClient



json 형태의 api 를 동기 및 비동기로 가져오는 방법입니다.


/// Author:         Anthony Baker
/// Date:           May 4th, 2013
/// Description:    JsonAPIClient - Sample JSON API Consumption

using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;

namespace JsonApiClient
{
    public static class WeatherApiClient
    {
        #region fields

        /// <summary>
        /// Base URL for the Weather Endpoint URL
        /// </summary>
        private const string baseUrl = "http://api.openweathermap.org/data/2.1/find/city?lat={0}&lon={1}&cnt={2}";

        #endregion

        #region methods

        /// <summary>
        /// Retrieves the Weather Forecast data synchronously.
        /// </summary>
        /// <param name="latitude">latitude of the geolocation</param>
        /// <param name="longitude">longitud of the geolocation</param>
        /// <param name="stationQuantity">number of weather stations to be included</param>
        public static void GetWeatherForecast(double latitude, double longitude, int stationQuantity) 
        {
            // Customize URL according to geo location parameters
            var url = string.Format(baseUrl, latitude, longitude, stationQuantity);

            // Syncronious Consumption
            var syncClient = new WebClient();
            var content = syncClient.DownloadString(url);

            // Create the Json serializer and parse the response
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(WeatherData));
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
            {
                // deserialize the JSON object using the WeatherData type.
                var weatherData = (WeatherData)serializer.ReadObject(ms);
            }
        }

        /// <summary>
        /// Retrieves the Weather Forecast data asynchronously.
        /// </summary>
        /// <param name="latitude">latitude of the geolocation</param>
        /// <param name="longitude">longitud of the geolocation</param>
        /// <param name="stationQuantity">number of weather stations to be included</param>
        public static void GetWeatherForecastAsync(double latitude, double longitude, int stationQuantity)
        {
            // Customize URL according to geo location parameters
            var url = string.Format(baseUrl, latitude, longitude, stationQuantity);

            // Async Consumption
            var asyncClient = new WebClient();
            asyncClient.DownloadStringCompleted += asyncClient_DownloadStringCompleted;
            asyncClient.DownloadStringAsync(new Uri(url));

            // Do something else...
        }

        /// <summary>
        /// Parses the weather data once the response download is completed.
        /// </summary>
        /// <param name="sender">object that originated the event</param>
        /// <param name="e">event arguments</param>
        static void asyncClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            // Create the Json serializer and parse the response
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(WeatherData));
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(e.Result)))
            {
                // deserialize the JSON object using the WeatherData type.
                var weatherData = (WeatherData)serializer.ReadObject(ms);
            }
        }

        #endregion
    }
}


이를 담는 클래스는 아래와 같습니다.


/// Author:         Anthony Baker
/// Date:           May 4th, 2013
/// Description:    JsonAPIClient - Sample JSON API Consumption

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace JsonApiClient
{
    /// <summary>
    /// Class to represent the WeatherData
    /// </summary>
    [DataContract]
    public class WeatherData
    {
        [DataMember]
        public double message { get; set; }
        [DataMember]
        public string cod { get; set; }
        [DataMember]
        public string calctime { get; set; }
        [DataMember]
        public int cnt { get; set; }
        [DataMember]
        public List<List> list { get; set; }
    }

    public class Coord
    {
        public double lon { get; set; }
        public double lat { get; set; }
    }

    public class Main
    {
        public double temp { get; set; }
        public int humidity { get; set; }
        public int pressure { get; set; }
        public double temp_min { get; set; }
        public double temp_max { get; set; }
    }

    public class Wind
    {
        public double speed { get; set; }
        public double gust { get; set; }
        public int deg { get; set; }
    }

    public class Clouds
    {
        public int all { get; set; }
    }

    public class Weather
    {
        public int id { get; set; }
        public string main { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
    }

    public class List
    {
        public int id { get; set; }
        public string name { get; set; }
        public Coord coord { get; set; }
        public double distance { get; set; }
        public Main main { get; set; }
        public int dt { get; set; }
        public Wind wind { get; set; }
        public Clouds clouds { get; set; }
        public List<Weather> weather { get; set; }
    }

}



이를 실행하는 main 함수 입니다.


/// Author:         Anthony Baker
/// Date:           May 4th, 2013
/// Description:    JsonAPIClient - Sample JSON API Consumption

using System;

namespace JsonApiClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // Define Location Params
            double latitude = 51.50853;
            double longitude = -0.12574;
            int stationQuantity = 10;

            // Get the weather forecaste data synchronously
            WeatherApiClient.GetWeatherForecast(latitude, longitude, stationQuantity);

            // Get the weather forecast data asynchronously
            WeatherApiClient.GetWeatherForecastAsync(latitude, longitude, stationQuantity);

            // Wait for user input - keep the program runnin
            Console.ReadLine();
        }
    }
}