设为首页 收藏本站
查看: 797|回复: 0

windows phone 7解析json

[复制链接]

尚未签到

发表于 2015-5-10 15:38:56 | 显示全部楼层 |阅读模式
  介绍一下今天的实例,实例是调用一个汇率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效果图:
DSC0000.jpg
xaml布局代码:




   
   
        
            
            
        
        
        
            
        
        
        
            
            
            
            
            
            
            
            
            
        
   

  


  两个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 + "(" + codeList.ToUpper() + ")");
                listPicker2.Items.Add(nameList + "(" + codeList.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
{"k__BackingField":"Chris","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 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(string json)
    {
        T obj = Activator.CreateInstance();
        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(myPerson);
// Deserialize
myPerson = JSONHelper.Deserialize(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

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-65554-1-1.html 上篇帖子: Windows 7 x64 (英文操作系统)安装SQLServer 2005版本相关解决方法 下篇帖子: Windows phone 7 关于json格式解析
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表