您的位置:首页 > Web前端 > JavaScript

C# 读取网页JSON数据

2017-12-28 14:14 453 查看
场景描述:

公司和别的系统需要对接,现在对方提供一个网址,数据都是json字符串,我需要对json数据进行处理。

提供的json数据如下格式



一、读取网址中的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数据

/// <summary>
/// Json 字符串 转换为 DataTable数据集合
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
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<ArrayList>(json);
if (arrayList.Count > 0)
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == 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数据,无论做什么处理都很方便了, 这里处理数据就先省略了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: