C# 解析与生成JSON

介绍一下今天的实例,实例是调用一个汇率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值

        }
    }


}


© 2011, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记