0%

Windows Phone 7解析Json实例 货币转换小程序源码下载

这个实例是利用前文提到的汇率API(http://xurrency.com/)实现货币转换,因为该API免费用户每天10次的限制,本程序其实是没有什么实用性的,当然,你可以考虑购买他们的服务,好像每年29.99欧元(老外的钱比较好赚)。在Windows Phone 7上解析JSON跟普通的桌面程序有些不同,因为命名空间System.Runtime.Serialization.Json不在System.Runtime.Serialization里,而是在System.Servicemodel.Web里,所以在添加引用的时候必须同时引用System.Runtime.Serialization和System.Servicemodel.Web。 上个UI效果图: xaml布局代码:

<phone:PhoneApplicationPage 
    x:Class="PhoneApp1.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:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
    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">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="PageTitle" Text="货币换算器" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <toolkit:ListPicker Header="现有货币"  Name="listPicker1" Margin="9,22,268,475">
            </toolkit:ListPicker>
            <toolkit:ListPicker Header="兑换货币" Margin="257,19,20,486" Name="listPicker2">
            </toolkit:ListPicker>
            <TextBlock Height="36" HorizontalAlignment="Left" Margin="161,187,0,0" Name="textBlock1" Text="输入金额:" VerticalAlignment="Top" Width="143" />
            <TextBox Height="76" HorizontalAlignment="Left" Margin="51,229,0,0" Name="textBox1" Text="" VerticalAlignment="Top" Width="351" />

            <TextBlock Height="110" HorizontalAlignment="Left" Margin="28,348,0,0" Name="textBlock2" Text="" VerticalAlignment="Top" Width="408" />
            <Button Content="兑换" HorizontalAlignment="Left" Margin="100,518,0,35" Name="button1" Width="231" Click="button1_Click" />
            <ProgressBar Height="28" HorizontalAlignment="Left" Margin="7,368,0,0" Name="progressBar1" VerticalAlignment="Top" Width="441" Foreground="Green" Visibility="Collapsed"  IsIndeterminate="True" />
        </Grid>
    </Grid>
 

</phone:PhoneApplicationPage>

两个ListPicker 两个TextBlock,一个TextBox,一个Button,一个ProgressBar,ListPicker的使用请参考Windows Phone 7下拉菜单的实现 Silverlight for Windows Phone Toolkit中ListPicker的使用 C#代码:

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 System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;


namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        string[] codeList;
        string[] nameList;
        public MainPage()
        {
            InitializeComponent();
            nameList = new string[19]{ "人民币", "欧元", "美元", "英镑", "澳元", "港币", "日元", "新台币", "加拿大元", "韩元", "瑞士法郎", "丹麦克朗", "印度卢比", "新西兰元", "新加坡元", "泰铢", "南非兰特", "斯里兰卡卢比", "马来西亚林吉特" };
            codeList = new string[19]{ "cny", "eur", "usd", "gbp","aud", "hdk", "jpy", "twd", "cad", "krw", "chf", "dkk", "inr", "nzd", "sgd", "thb", "zar", "lkr", "myr" };
            //定义两数组,一个存中文货币名,一个存英文代码
            for (int i = 0; i < nameList.Length; i++)
            {
                listPicker1.Items.Add(nameList[i] + "(" + codeList[i].ToUpper() + ")");
                listPicker2.Items.Add(nameList[i] + "(" + codeList[i].ToUpper() + ")");
            }
            //填充两个ListPicker
            //ListPicker并不是Windows Phone 7标准控件,使用方法请参考 http://www.pocketdigi.com/20110910/466.html
        }

        [DataContract(Namespace = "http://www.pocketdigi.com")]
        public class Currency
        //不public会抛System.Security.SecurityException异常
        {
            [DataMember(Order = 0)]
            public result result { get; set; }
            [DataMember(Order = 1)]
            public int code { get; set; }
            [DataMember(Order = 2)]
            public string status { get; set; }

        }
        [DataContract(Namespace = "http://www.pocketdigi.com")]
        public class result
        {
            [DataMember(Order = 0)]
            public string updated_at { get; set; }
            [DataMember(Order = 1)]
            public float value { get; set; }
            [DataMember(Order = 2)]
            public string target { get; set; }
            [DataMember(Order = 3)]
            public string Base { get; set; }

        }
        //与前文 C# 解析与生成JSON http://www.pocketdigi.com/20110921/484.html 相同

        //定义序列化方法,这里用不着
        //private static string Serialize(Currency currency)
        //{
        //    using (MemoryStream ms = new MemoryStream())
        //    {
        //        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Currency));
        //        serializer.WriteObject(ms, currency);
        //        ms.Position = 0;

        //        using (StreamReader reader = new StreamReader(ms))
        //        {
        //            return reader.ReadToEnd();
        //        }
        //    }
        //}

        //定义反序列化方法
        private static Currency Deserialize(string jsonString)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Currency));
                return (Currency)serializer.ReadObject(ms);
            }
        }


        private void button1_Click(object sender, RoutedEventArgs e)
        {
            progressBar1.Visibility = Visibility.Visible;
            //显示进度条
            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            //添加下载完成事件处理器,在异步数据下载完成时触发
            
            string url = "http://xurrency.com/api/"+codeList[listPicker1.SelectedIndex]+"/"+codeList[listPicker2.SelectedIndex]+"/"+textBox1.Text;
            webClient.DownloadStringAsync(new Uri(url));
        }
        private void webClient_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
        {
            string result = e.Result;
            result=result.Replace("base", "Base");
            //base是c#关键字,必须替换
            var mStream = new MemoryStream(Encoding.UTF8.GetBytes(result));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Currency));
            Currency readCurrency = (Currency)serializer.ReadObject(mStream);
            //反序列化,得到Currency类实例
            textBlock2.Text = readCurrency.result.value.ToString();
            textBlock2.Text += "\n汇率更新时间:\n";
            textBlock2.Text += readCurrency.result.updated_at;
            //更新UI

            progressBar1.Visibility = Visibility.Collapsed;
            //隐藏进度条
        }


    }
}

最后附上源码: [download id=”24”]