c#抓取网页数据(软件()和别的系统需要对接,数据都是json字符串)

优采云 发布时间: 2022-04-19 01:26

  c#抓取网页数据(软件()和别的系统需要对接,数据都是json字符串)

  场景描述:

  公司需要与其他系统连接。现在对方提供了一个网站。数据都是json字符串。我需要处理json数据。

  提供的json数据格式如下

  

  一、读取URL中的json数据

   public string getHtml(string html)//传入网址

{

string pageHtml = "";

WebClient MyWebClient = new WebClient();

MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据

Byte[] pageData = MyWebClient.DownloadData(html); //从指定网站下载数据

MemoryStream ms = new MemoryStream(pageData);

using (StreamReader sr = new StreamReader(ms, Encoding.GetEncoding("GB2312")))

{

pageHtml = sr.ReadLine();

}

return pageHtml;

}

  二、将json数据转成DataTable数据

   ///

/// Json 字符串 转换为 DataTable数据集合

///

///

///

public static DataTable ToDataTableTwo(string json)

{

DataTable dataTable = new DataTable(); //实例化

DataTable result;

try

{

JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();

javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值

ArrayList arrayList = javaScriptSerializer.Deserialize(json);

if (arrayList.Count > 0)

{

foreach (Dictionary dictionary in arrayList)

{

if (dictionary.Keys.Count() == 0)

{

result = dataTable;

return result;

}

//Columns

if (dataTable.Columns.Count == 0)

{

foreach (string current in dictionary.Keys)

{

dataTable.Columns.Add(current, dictionary[current].GetType());

}

}

//Rows

DataRow dataRow = dataTable.NewRow();

foreach (string current in dictionary.Keys)

{

dataRow[current] = dictionary[current];

}

dataTable.Rows.Add(dataRow); //循环添加行到DataTable中

}

}

}

catch

{

}

result = dataTable;

return result;

}

  三、调用写好的方法将json转DataTable数据,得到的json字符串,name字段对应的值需要处理,转DataTable后为中文。

   string jsonStr = getHtml("http://......");//url

DataTable dt = ToDataTableTwo(jsonStr);

  四、已经转化为DataTable数据,无论做什么都很方便,所以这里省略数据处理。

  转载于:

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线