json.net 获取json中你想要的数据
简单介绍下json
json是一种轻量级的数据交换格式,由N组键值对组成的字符串,完全独立于语言的文本格式。
在很久很久以前,调用第三方API时,我们通常是采用xml进行数据交互,但往往xml包含更多冗余的标记字符,在传输较大数据时,相较于xml,json显得更加简洁,轻量。
与此同时,javascript能更好的支持json,以及它更加便捷的解析方式,这使得我们在编程过程中能够更加方便,快捷的进行开发。
慢慢地,我们已经渐渐向json转变,越来越多的人开始使用json进行数据交互了。
在.net中调用json
最简单的方式就是在项目右键点击“管理NuGet程序包”中搜索json.net然后安装即可,等到项目的引用中出现这个东西的时候就可以在程序里using Newtonsoft.Json了。
也可以去官网下载。
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace apiTest1
{
class weather
{
public static string request(string url, string param)
{
string strURL = url + '?' + param;
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Method = "GET";
// 添加header
request.Headers.Add("apikey", "e3004ad5f49fd704237836b1c84bf09f");
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
StreamReader Reader = new StreamReader(s, Encoding.UTF8);
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
return strValue;
}
public 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);
}
}
}
}
}
只需要加上这几句话,
你就可以从繁杂的数据中取到你想
要的。
每天进步一点点!