Edward_jie

for you, my Hall of Frame

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

介绍一下今天的实例,实例是调用一个汇率API(http://xurrency.com/)来实现货币转换,该API返回的就是JSON数据。但是免费用户使用该API有每天使用10次的限制,所以可能您在测试的时候返回错误,是因为达到了限制。
解析与生成JSON需要System.Runtime.Serialization.Json命名空间,但得先从菜单添加引用”System.Runtime.Serialization”。Windows Phone 7上稍有不同,参考:Windows Phone 7解析Json实例 货币转换小程序源码下载
代码:

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Net;

namespace Json
{
class Program
{

[DataContract(Namespace = "http://www.pocketdigi.com")]
public class Currency

{
[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; }
//返回的是base,但因base是c#关键字,这里用Base代替,在下面拿到api返回数据时也替换成Base

}
//API反回的结果形似:{"result":{"updated_at":"2011-09-21T09:04:00Z","value":637.92,"target":"cny","base":"usd"},"code":0,"status":"ok"}
//定义两个类,一个为Currency,包括返回的所有信息,一个为result类,包括updated_at,value,target,base

static void Main(string[] args)
{
var currency = new Currency()
{
result = new result() { updated_at = "2011-09-14T14:03:00Z", value = 639.478f, target = "CNY", Base = "USD" },
code = 0,
status = "OK"

};
//通过传入参数实例化一个Currency类
var serializer = new DataContractJsonSerializer(typeof(Currency));
var stream = new MemoryStream();
serializer.WriteObject(stream, currency);
//序列化,并写入到stream

byte[] dataBytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(dataBytes, 0, (int)stream.Length);
string dataString = Encoding.UTF8.GetString(dataBytes);
//从stream读入到string,即生成JSON
Console.WriteLine("JSON string is:");
Console.WriteLine(dataString);

//string s="{\"result\":{\"updated_at\":\"2011-09-14T14:03:00Z\",\"value\":639.47,\"target\":\"cny\",\"Base\":\"usd\"},\"code\":0,\"status\":\"ok\"}";

WebClient webClient = new WebClient();
string s = webClient.DownloadString("http://xurrency.com/api/usd/cny/100");
//下载API返回数据,因为API每天每IP限制调用10次,所以超过10次会返回错误
//api调用方法 http://xurrency.com/api/原货币小写代码/目标货币小写代码/数额
s = s.Replace("base", "Base");
//因为base是C#关键字, 所以替换一下
Console.WriteLine(s);
//输出API返回字符串

var mStream = new MemoryStream(Encoding.UTF8.GetBytes(s));
DataContractJsonSerializer serializer2 = new DataContractJsonSerializer(typeof(Currency));
Currency readCurrency = (Currency)serializer2.ReadObject(mStream);
//反序列化成Currency类实例
Console.WriteLine(readCurrency.result.value);
//读取value值

}
}


}


 

具体代码介绍:

这个实例是利用前文提到的汇率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;
//隐藏进度条
}


}
}

 

 

最后附上源码:
Currency (4)

原文链接:http://www.pocketdigi.com/20110921/484.html

 

最后带上一篇老外的文章:

In ASP.NET AJAX Extensions v1.0 for ASP.NET 2.0 there is the JavaScriptSerializer class that provides JSON serialization and deserialization functionality. However, in .NET 3.5 the JavaScriptSerializer has been marked obsolete. The new object to use for JSON serialization in .NET 3.5 is the DataContractJsonSerliaizer object. I'm still new to the DataContractJsonSerializer, but here's a summary of what I've learned so far...

Object to Serialize

Here's a simple Person object with First Name and Last Name properties.

public class Person
{
public Person() { }
public Person(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
public string FirstName { get; set; }
public string LastName { get; set; }
}

 

Now in order to serialize our object to JSON using the DataContractJsonSerializer we must either mark it with the Serializable attribute or the DataContract attribute. If we mark the class with the DataContract attribute, then we must mark each property we want serialized with the DataMember attribute.

/// Marked with the Serializable Attribute
[Serializable]
public class Person
{
public Person() { }
public Person(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
public string FirstName { get; set; }
public string LastName { get; set; }

}

/// Marked with the DataContact Attribute
[DataContract]
public class Person
{
public Person() { }
public Person(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}

[DataMember]
public string FirstName { get; set; }

[DataMember]
public string LastName { get; set; }
}

 

Serialization Code


Jere's the most basic code to serialize our object to JSON:

Person myPerson = new Person("Chris", "Pietschmann");

/// Serialize to JSON
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myPerson);
string json = Encoding.Default.GetString(ms.ToArray());


Our resulting JSON looks like this:

/// Result of Person class marked as Serializable
{"<FirstName>k__BackingField":"Chris","<LastName>k__BackingField":"Pietschmann"}


/// Result of Person class marked as DataContract with
/// each Property marked as DataMember
{"FirstName":"Chris","LastName":"Pietschmann"}


As you can see the first serialization with the class marked with the Serializable attribute isn't quite what we were expecting, but is still JSON. This serialization actually isn't compatible with the client-side JSON Serializer in ASP.NET AJAX.

As you can see the second serialization with the class marked with the DataContract attribute is exactly what we were expecting, and is the same JSON that the old JavaScriptSerializer object would have generated. This is the method of JSON serialization using the DataContractJsonSerializer that you'll need to do if you are going to pass the resulting JSON down to the client to be consumed with ASP.NET AJAX.

Deserialization Code

Here's the most basic code to deserialize our object from JSON:

Person myPerson = new Person();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
myPerson = serializer.ReadObject(ms) as Person;
ms.Close();


Controlling the property names in the resulting JSON

When using the DataContract and DataMember attributes, you can tell the DataMember attribute the specific name you want that property to have within the JSON serialization by setting its "Name" named parameter.

Here's an example that will give the name of "First" to the "FirstName" property within the JSON serialization:

[DataMember(Name = "First")]
public string FirstName { get; set; }The resulting JSON looks like this:

{"First":"Chris","LastName":"Pietschmann"}


Here's the code for some Helper methods using Generics to do all the dirty work for you

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

public class JSONHelper
{
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}

public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
return obj;
}
}

/// Our Person object to Serialize/Deserialize to JSON
[DataContract]
public class Person
{
public Person() { }
public Person(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}

[DataMember]
public string FirstName { get; set; }

[DataMember]
public string LastName { get; set; }
}


/// Sample code using the above helper methods
/// to serialize and deserialize the Person object

Person myPerson = new Person("Chris", "Pietschmann");

// Serialize
string json = JSONHelper.Serialize<Person>(myPerson);

// Deserialize
myPerson = JSONHelper.Deserialize<Person>(json);


What Assembly References does my application need for this?

From the namespace that contains DataContractJsonSerializer you can probably tell that you need to add a reference to the System.Runtime.Serialization assembly. However, you also need to add a reference to the System.ServiceModel.Web assembly.

老外原文链接:http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx

posted on 2011-11-18 14:12  Edward_诺  阅读(2515)  评论(0编辑  收藏  举报