运用WebClient获取天气和json数据解析

首先附上代码
前台:
    

<phone:PhoneApplicationPage 
    x:Class="WeatherForecast.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:my="clr-namespace:ForeCastTemplate;assembly=ForeCastTemplate"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True" xmlns:my1="clr-namespace:ForeCastTemplate;assembly=ForeCastTemplate" Loaded="PhoneApplicationPage_Loaded">

    <!--LayoutRoot 是包含所有页面内容的根网格-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel 包含应用程序的名称和页标题-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="我的应用程序" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="页面名称" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - 在此处放置其他内容-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid x:Name="aa">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="250" />
                    <ColumnDefinition Width="200" />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="200" />
                    <RowDefinition Height="100" />
                    <RowDefinition Height="100" />
                    <RowDefinition Height="100" />
                    <RowDefinition Height="100" />
                </Grid.RowDefinitions>
                <my:ForecastTemplate x:Name="day1" Grid.Column="1" Grid.Row="1" Height="100" Width="200" />
                <my:ForecastTemplate x:Name="day2" Grid.Column="1" Grid.Row="2" Height="100" Width="200" />
                <my:ForecastTemplate x:Name="day3" Grid.Column="1" Grid.Row="3" Height="100" Width="200" />
                <my:ForecastTemplate x:Name="day4" Grid.Column="1" Grid.Row="4" Height="100" Width="200" HorizontalAlignment="Left" />
                <Image x:Name="todayImage" Height="200" Width="250" />
                <TextBlock x:Name="todayTemp" Grid.Column="0" Grid.Row="1" Width="250" Height="100" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="40" />
                <TextBlock x:Name="todayWhe" Grid.Column="1" Grid.Row="0" Width="250" Height="200" TextWrapping="Wrap" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="24" />
                <TextBlock x:Name="todaydate" Grid.Column="0" Grid.Row="2" Width="250" Height="100" TextWrapping="Wrap" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="24" />
                <TextBlock x:Name="wtInfo" Grid.Column="0" Grid.Row="3" Grid.RowSpan="2" TextWrapping="Wrap" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="24" />
            </Grid>
        </Grid>
    </Grid>
 
    <!--演示 ApplicationBar 用法的示例代码-->
    <!--<phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="按钮 1"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="按钮 2"/>
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarMenuItem Text="菜单项 1"/>
                <shell:ApplicationBarMenuItem Text="菜单项 2"/>
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>-->

</phone:PhoneApplicationPage>
后台代码:
    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Windows.Media.Imaging;

namespace WeatherForecast
{
    public partial class MainPage : PhoneApplicationPage
    {
        WeathorInfo weather = null;
        string[] weekMsg = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" };

        // 构造函数
        public MainPage()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            WebClient wb = new WebClient();
            wb.DownloadStringCompleted+=new DownloadStringCompletedEventHandler(wb_DownloadStringCompleted);
            wb.DownloadStringAsync(new Uri("http://m.weather.com.cn/data/101040200.html", UriKind.Absolute));
        }

        void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Result.Length <= 0 || e.Error != null || e.Cancelled)
            {
                MessageBox.Show("获取天气预报失败");
                return;
            }

            JObject json = JObject.Parse(e.Result);
            weather = new WeathorInfo {
                city = (string)json["weatherinfo"]["city"],
                cityid = (string)json["weatherinfo"]["cityid"],
                date_y = (string)json["weatherinfo"]["date_y"],
                week = (string)json["weatherinfo"]["week"],
                info = (string)json["weatherinfo"]["index48_d"],
                wind1 = (string)json["weatherinfo"]["wind1"],
                temp1 = (string)json["weatherinfo"]["temp1"],
                temp2 = (string)json["weatherinfo"]["temp2"],
                temp3 = (string)json["weatherinfo"]["temp3"],
                temp4 = (string)json["weatherinfo"]["temp4"],
                temp5 = (string)json["weatherinfo"]["temp5"],
                weather1 = (string)json["weatherinfo"]["weather1"],
                weather2 = (string)json["weatherinfo"]["weather2"],
                weather3 = (string)json["weatherinfo"]["weather3"],
                weather4 = (string)json["weatherinfo"]["weather4"],
                weather5 = (string)json["weatherinfo"]["weather5"]
            };
            //MessageBox.Show(weather.city);
            UpdateUI();

        }

        void UpdateUI()
        {
            day1.Temp = weather.temp2;
            day2.Temp = weather.temp3;
            day3.Temp = weather.temp4;
            day4.Temp = weather.temp5;

            todayTemp.Text = weather.temp1;
            todayWhe.Text = weather.weather1 + Environment.NewLine + weather.wind1;
            todaydate.Text = weather.date_y + Environment.NewLine + weather.week;
            wtInfo.Text = weather.info;

            PageTitle.Text = weather.city;

            int i;

            for (i = 0; i < 7; i++)
            {
                if (weekMsg[i] == weather.week)
                {
                    break;
                }
            }

            day1.Weekday = weekMsg[(i + 1) % 7];
            day2.Weekday = weekMsg[(i + 2) % 7];
            day3.Weekday = weekMsg[(i + 3) % 7];
            day4.Weekday = weekMsg[(i + 4) % 7];

            day1.ImageUri = GetImgUri(weather.weather2);
            day2.ImageUri = GetImgUri(weather.weather3);
            day3.ImageUri = GetImgUri(weather.weather4);
            day4.ImageUri = GetImgUri(weather.weather5);

            todayImage.Source = new BitmapImage(new Uri(GetImgUri(weather.weather1), UriKind.Relative));

        }


        /// <summary>
        /// 返回天气图片的Uri。图片的Building属性为Resource
        /// </summary>
        /// <param name="weather"></param>
        /// <returns></returns>
        String GetImgUri(string weather)
        {
            string uri = "/WeatherForecast;component/Images/";
            if (weather == "晴")
            {
                return uri + "sunday.jpg";
            }
            else if (weather == "阴")
            {
                return uri + "overcast.jpg";
            }
            else if (weather == "雷阵雨")
            {
                return uri + "ThunderShower.jpg";
            }
            else if (weather.Contains("多云"))
            {
                return uri + "cloudy.jpg";
            }
            else if (weather.Contains("雨"))
            {
                return uri + "Rain.jpg";
            }
            else
            {
                return uri + "cloudy.jpg";
            }
        }
    }
}
用到的解析数据的实体类
    
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace WeatherForecast
{
    public class WeathorInfo
    {
        public string city { get; set; }
        public string cityid { get; set; }
        public string date_y { get; set; }
        public string week { get; set; }
        public string temp1 { get; set; }
        public string temp2 { get; set; }
        public string temp3 { get; set; }
        public string temp4 { get; set; }
        public string temp5 { get; set; }
        public string weather1 { get; set; }
        public string weather2 { get; set; }
        public string weather3 { get; set; }
        public string weather4 { get; set; }
        public string weather5 { get; set; }
        public string wind1 { get; set; }
        public string info { get; set; } 
    }
}


知识共享许可协议
《运用WebClient获取天气和json数据解析》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
相邻依据:发表时间
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

1 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     175.01ms