今天小梦给大家分享一个简单的天气预报应用源码:调用的是百度API.整个应用都没有什么难点.只是一个简单的网络请求和json数据处理.在WP8.1有小娜的情况下,天气预报应用还有意义吗?我认为还是有点意义的,至少数据更详细,而要想要用户喜欢,必须有比小娜更人性化的提醒和精美的UI.UI必须要精美.当然小梦今天分享的UI很简单.大家可以根据自己的想象去处理UI.之所以分享出来,是分享JSON的数据处理.在WP8.1开发XML读取中央气象城市代码文件中,分享了XML文件和JSON数据解析的方法,不过其中是直接处理的JSON数据,今天分享的是利用对象序列化JSON数据.当然,如有不当或错误,欢迎指正.

JSON数据本身:

{
"error": 0,
"status": "success",
"date": "2014-09-13",
"results": [
{
"currentCity": "西安市",
"pm25": "25",
"index": [
{
"title": "穿衣",
"zs": "较舒适",
"tipt": "穿衣指数",
"des": "建议着薄外套、开衫牛仔衫裤等服装。年老体弱者应适当添加衣物,宜着夹克衫、薄毛衣等。"
},
{
"title": "洗车",
"zs": "不宜",
"tipt": "洗车指数",
"des": "不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。"
},
{
"title": "旅游",
"zs": "一般",
"tipt": "旅游指数",
"des": "温度适宜,有微风同行,但较强降雨的天气将给您的出行带来很多的不便,若坚持旅行建议带上雨具。"
},
{
"title": "感冒",
"zs": "较易发",
"tipt": "感冒指数",
"des": "天气较凉,较易发生感冒,请适当增加衣服。体质较弱的朋友尤其应该注意防护。"
},
{
"title": "运动",
"zs": "较不宜",
"tipt": "运动指数",
"des": "有较强降水,建议您选择在室内进行健身休闲运动。"
},
{
"title": "紫外线强度",
"zs": "最弱",
"tipt": "紫外线强度指数",
"des": "属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。"
}
],
"weather_data": [
{
"date": "周六 09月13日 (实时:16℃)",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhongyu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhongyu.png",
"weather": "中雨",
"wind": "西南风微风",
"temperature": "15℃"
},
{
"date": "周日",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhongyu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhongyu.png",
"weather": "中雨",
"wind": "西南风微风",
"temperature": "18 ~ 15℃"
},
{
"date": "周一",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhongyu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhongyu.png",
"weather": "中雨",
"wind": "西南风微风",
"temperature": "19 ~ 15℃"
},
{
"date": "周二",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhongyu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhongyu.png",
"weather": "中雨",
"wind": "西南风微风",
"temperature": "17 ~ 15℃"
}
]
}
]
}

我们根据JSON数据构建对象:(对象名称最好和数据名称保持一致)

  public   class WeatherData
{
public int error { get; set; }
public string status { get; set; }
public string date { get; set; }
public List<resultsList> results { get; set; } public class resultsList
{ public string currentCity{ get; set; } public string pm25 { get; set; }
public List<indexList> index { get; set; }
public List<weather_dataList> weather_data { get; set; }
}
public struct indexList
{
public string title { get; set; }
public string zs { get; set; }
public string tipt { get; set; }
public string des { get; set; } } public struct weather_dataList
{
public string date { get; set; }
public string weather { get; set; }
public string wind { get; set; }
public string temperature { get; set; }
public Uri dayPictureUrl { get; set; }
public Uri nightPictureUrl { get; set; }
}
}

应用前台代码:

<Pivot>
<PivotItem Header="天气" >
<ListView Name="listWeather">
<ListView.Header >
<StackPanel>
<TextBlock x:Name="textCity" FontSize=""></TextBlock>
<TextBlock x:Name="textPm" FontSize="" Foreground="Orange"></TextBlock>
</StackPanel>
</ListView.Header>
<ListView.ItemTemplate >
<DataTemplate>
<Border Width="" BorderThickness="" BorderBrush="#FF2996AE">
<StackPanel >
<TextBlock Text="{Binding date}" FontSize=""></TextBlock>
<TextBlock Text="{Binding weather}" FontSize=""></TextBlock>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding dayPictureUrl}" Stretch="Uniform"
Width="" Height=""></Image>
<Image Source="{Binding nightPictureUrl}" Stretch="Uniform"
Width="" Height=""></Image>
</StackPanel>
<TextBlock Text="{Binding wind}" FontSize=""></TextBlock>
<TextBlock Text="{Binding temperature }" FontSize=""></TextBlock> </StackPanel>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</PivotItem>
<PivotItem Header="指数">
<ListView Name="listIndex">
<ListView.ItemTemplate >
<DataTemplate>
<Border>
<StackPanel >
<TextBlock Text="{Binding tipt }" FontSize="" Foreground="#FF2996AE"></TextBlock>
<TextBlock Text="{Binding zs}" FontSize="" Foreground="Green"></TextBlock>
<TextBlock Text="{Binding des }" FontSize="" TextWrapping="Wrap"></TextBlock>
</StackPanel>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</PivotItem>
</Pivot> </Grid>
<Page.BottomAppBar>
<CommandBar Background="#FF2996AE">
<AppBarButton Icon="Sync" Label="刷新" Click="AppBarButton_Click"/>
</CommandBar>
</Page.BottomAppBar>

后台处理代码:

  public sealed partial class MainPage : Page
{
private string latitude = null;
private string longitude = null;
private string responseText = null;
private HttpClient httpClient;
private HttpResponseMessage response; private Weather.WeatherData.resultsList weather; public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required; httpClient = new HttpClient();
var headers = httpClient.DefaultRequestHeaders;//获取每个请求标头的集合
headers.UserAgent.ParseAdd("ie");
headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
} protected async override void OnNavigatedTo(NavigationEventArgs e)
{
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracyInMeters = ;
try
{
Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(),
timeout: TimeSpan.FromSeconds());
latitude = geoposition.Coordinate.Point.Position.Latitude.ToString();
longitude = geoposition.Coordinate.Point.Position.Longitude.ToString();
}
catch (UnauthorizedAccessException)
{
Debug.WriteLine( "无法获取位置信息!");
}
} private async void AppBarButton_Click(object sender, RoutedEventArgs e)
{
response = new HttpResponseMessage(); Uri resourceUri;
String Address = "http://api.map.baidu.com/telematics/v3/weather?location="+longitude+","+latitude+"&output=json&ak=你的KEY";
Uri.TryCreate(Address.Trim(), UriKind.Absolute, out resourceUri); try
{
response = await httpClient.GetAsync(resourceUri); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync(); }
catch (Exception ex)
{
Debug.WriteLine("网络请求失败!" + ex.Message.ToString()); } DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(WeatherData));
WeatherData weatherData = obj.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(responseText))) as WeatherData;
weather = weatherData.results.FirstOrDefault();
listWeather.ItemsSource = weather.weather_data;
listIndex.ItemsSource = weather.index;
textCity.Text = weather.currentCity.ToString();
textPm.Text= "PM2.5:"+weather.pm25.ToString(); }

运行效果如下:

完整源码下载:WP8.1天气预报应用.

最新文章

  1. 【Java EE 学习 83 下】【SpringMVC】【使用注解替代已过时的API】【SpringMVC、Hibernate整合】
  2. Android 毛玻璃效果
  3. 基于CentOS与VmwareStation10搭建Oracle11G RAC 64集群环境:4.安装Oracle RAC FAQ-4.6.重新配置与缷载11R2 Grid Infrastructure
  4. Spring Batch Framework– introduction chapter(下)
  5. svn的初级使用
  6. java——Arrays.asList()方法
  7. hibernate事务控制
  8. ios-Ineligible Devices 不被识别的设备
  9. JavaBean转JSON方式
  10. 快速排序实现及其pivot的选取
  11. python中filter、map、reduce的区别
  12. 【C#】解析C#中LING的使用
  13. 【C#数据结构系列】图
  14. console.log()显示图片以及为文字加样式
  15. pyhthon lambda
  16. windows emacs 中拷贝文件
  17. 移植tslib和Qt5.6到三星s5pv210开发板
  18. 下了个蓝屏代码查看工具,就中病毒了。。。什么鬼病毒,竟然还是用的VBS
  19. unity代码设置鼠标样式
  20. php分页类的实现与调用 (自我摘记)

热门文章

  1. vue.js最最最最简单实例
  2. Linux 常用解压缩归档命令
  3. Filebeat的下载(图文讲解)
  4. 虚拟机上的企业网络管理系统(cisco works 2000安装配置)
  5. php 生成文件txt到指定目录
  6. Appium_python3 抓取客户端toast
  7. 洛谷 P2819 图的m着色问题
  8. 洛谷 P2097 资料分发1
  9. oracle学习之路(二)------数组类型/记录类型的使用
  10. Incapsula免费日本CDN加速和CDNZZ香港CDN节点加速