C#でJsonのデシリアライズ

概要

このサイトでは、Jsonオブジェクトを取得し、C#.NETで取り扱いができるようにする処理の方法を考えてみます。

サイト

OpenWeather…Jsonオブジェクトの取得先。
Json2csharp…Jsonオブジェクトを、C#で扱えるように型を作ってくれるサービス。

手順

1.プロジェクトを用意します。(コンソール)
2.JsonのURLを用意する。
3.C#のクラスを作る。
4.データを表示する。

プロジェクトの用意

C#でコンソールプロジェクトを作成してください。

JsonのURL

http://api.openweathermap.org/data/2.5/weather?q=Tokyo

C#のクラス

上記、URLをJson2csharpに貼り付けますと、自動的にクラスが作成され、表示されます。

コーディング

気温は、絶対零度を引いた値が、現在の気温になります。
それらしい気温が表示されていますか?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
namespace JsonCS
{
    public class Coord
    {
        public double lon { get; set; }
        public double lat { 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 Main
    {
        public double temp { get; set; }
        public int pressure { get; set; }
        public int humidity { get; set; }
        public double temp_min { get; set; }
        public double temp_max { get; set; }
    }
    public class Wind
    {
        public double speed { get; set; }
        public int deg { get; set; }
    }
    public class Clouds
    {
        public int all { get; set; }
    }
    public class Sys
    {
        public int type { get; set; }
        public int id { get; set; }
        public double message { get; set; }
        public string country { get; set; }
        public int sunrise { get; set; }
        public int sunset { get; set; }
    }
    public class RootObject
    {
        public Coord coord { get; set; }
        public List<Weather> weather { get; set; }
        public string @base { get; set; }
        public Main main { get; set; }
        public int visibility { get; set; }
        public Wind wind { get; set; }
        public Clouds clouds { get; set; }
        public int dt { get; set; }
        public Sys sys { get; set; }
        public int id { get; set; }
        public string name { get; set; }
        public int cod { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            byte[] buff = new byte[4096];
            WebClient client = new WebClient();

            buff = client.DownloadData("http://api.openweathermap.org/data/2.5/weather?q=Tokyo");
            Encoding utf8 = Encoding.GetEncoding("UTF-8");
            String json = utf8.GetString(buff);
            var m = JsonConvert.DeserializeObject<RootObject>(json);

            Console.WriteLine((int)(m.main.temp - 273.15));
        }
    }
}