這裡以抓取繁化姬API的JSON資料為例
這裡我們使用NuGet安裝Newtonsoft.Json
並使用
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
主要流程
- 利用HttpWebRequest取得網頁內容
- 利用Newtonsoft.Json分析我們要的內容
完整的程始碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Zhconvert_Api
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class SearchResult
{
public string text { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
string Api_Url = @"https://api.zhconvert.org/convert?";
string Converter_Parameter = @"converter="+ "Taiwan";
string Json_Format = @"&prettify="+ "1";
string Translate_Text = @"&text="+ "内存不足!";
string Full_Url = Api_Url + Converter_Parameter + Json_Format + Translate_Text;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Full_Url);
request.Timeout = 10000;
request.Method = "GET";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Windows NT 5.2; Windows NT 6.0; Windows NT 6.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; MS-RTC LM 8; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 4.0C; .NET CLR 4.0E)";
HttpWebResponse webresponse = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(webresponse.GetResponseStream(), Encoding.UTF8);
string retString = streamReader.ReadToEnd();
webresponse.Close();
streamReader.Close();
JObject Search_Json = JObject.Parse(retString);
string Chinese_Text = (string)Search_Json["data"]["text"];
textBox1.Text = Chinese_Text;
}
}
}
我們可以看到底下主要抓取JSON的程式碼
JObject Search_Json = JObject.Parse(retString);
string Chinese_Text = (string)Search_Json["data"]["text"];
textBox1.Text = Chinese_Text;
- 先利用JObject轉換文字檔成JSON物件,裡面的retString是我們獲得繁化姬的內容
- 因為我們只要取得繁化姬data底下text的繁化結果而已,所以使用(string)Search_Json"data"
程式碼下載:
https://mega.nz/#!PaQmXIgJ!JJhGVpppFvFH9A8hR9bAojX5neCq7W8Y64N-Ix4xFzM