码迷,mamicode.com
首页 > Windows程序 > 详细

C#实现中国天气网JSON接口测试

时间:2015-12-13 07:13:31      阅读:406      评论:0      收藏:0      [点我收藏+]

标签:

接上一篇,经过反复的查看,最终从这篇文章中找到了一个可用的JSON接口,于是研究了一下JSON接口的测试,和上一篇XML接口测试的原理是一样的,只是需要安装一下Newtonsoft.Json:

技术分享

这个就是传说中的JSON.Net!在项目右键点击“管理NuGet程序包”中搜索json.net然后安装即可,等到项目的引用中出现这个东西的时候就可以在程序里using Newtonsoft.Json了。

还是老套路,不管有用没用,先把接口返回的JSON内容保存到本地一份。这里为了查看方便我直接在控制台打印出来了,方便查看JSON的结构并加以分析:

技术分享

通过JSON.Net对字符串进行反序列化(也可以强转),然后对内容加以分析即可,至于想测试,一般是比较值。这里就做一次遍历,不做比较了。代码如下:

using System;
using System.Text;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;

namespace JsonInterfaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            test(101010100);
        }

        private static void test(int interfaceNumber)
        {
            string url = "http://www.weather.com.cn/adat/cityinfo/" + interfaceNumber + ".html";
            string localContent = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\test.txt";
            try
            {
                WebClient MyWebClient = new WebClient();
                Byte[] pageData = MyWebClient.DownloadData(url);
                string pageHtml = Encoding.UTF8.GetString(pageData);
                using (StreamWriter sw = new StreamWriter(localContent))
                {
                    sw.WriteLine(pageHtml);
                }
                //JObject jObj = JObject.Parse(pageHtml);
                JObject jObj = JsonConvert.DeserializeObject(pageHtml) as JObject;
                Console.WriteLine(jObj.ToString());
                ReadJson(jObj);
                Console.ReadLine();
            }
            catch (WebException webEx)
            {
                Console.WriteLine(webEx.Message.ToString());
            }
        }

        private static void ReadJson(JObject jObj)
        {
            foreach (var o in jObj)
            {
                Console.Write(o.Key+":");
                if (o.Value is JObject)
                {
                    Console.WriteLine();
                    ReadJson(JsonConvert.DeserializeObject(o.Value.ToString()) as JObject);
                }
                else
                {
                    Console.WriteLine(o.Value);
                }
            }
        }
    }
}

 

C#实现中国天气网JSON接口测试

标签:

原文地址:http://www.cnblogs.com/LanTianYou/p/5042224.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!