C# 讀取網頁JSON數據


場景描述:

    公司和別的系統需要對接,現在對方提供一個網址,數據都是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數據,無論做什么處理都很方便了, 這里處理數據就先省略了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM