[Json] C#ConvertJson|List轉成Json|對象|集合|DataSet|DataTable|DataReader轉成Json (轉載)...

點擊下載?ConvertJson.rar

本類實現了?
C#ConvertJson|List轉成Json|對象|集合|DataSet|DataTable|DataReader轉成Json|
等功能
大家先預覽一下

?

請看代碼

/// <summary>
/// 類說明:Assistant
/// 編 碼 人:蘇飛
/// 聯系方式:361983679  
/// 更新網站:[url=http://www.sufeinet.com/thread-655-1-1.html]http://www.sufeinet.com/thread-655-1-1.html[/url]
/// </summary>
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
using System.Collections;
using System.Data.Common;namespace SiteAppFunction
{//JSON轉換類public class ConvertJson{#region 私有方法/// <summary>/// 過濾特殊字符/// </summary>private static string String2Json(String s){StringBuilder sb = new StringBuilder();for (int i = 0; i < s.Length; i++){char c = s.ToCharArray();switch (c){case '\"':sb.Append("\\\""); break;case '\\':sb.Append("\\\\"); break;case '/':sb.Append("\\/"); break;case '\b':sb.Append("\\b"); break;case '\f':sb.Append("\\f"); break;case '\n':sb.Append("\\n"); break;case '\r':sb.Append("\\r"); break;case '\t':sb.Append("\\t"); break;default:sb.Append(c); break;}}return sb.ToString();}/// <summary>/// 格式化字符型、日期型、布爾型/// </summary>private static string StringFormat(string str, Type type){if (type == typeof(string)){str = String2Json(str);str = "\"" + str + "\"";}else if (type == typeof(DateTime)){str = "\"" + str + "\"";}else if (type == typeof(bool)){str = str.ToLower();}else if (type != typeof(string) && string.IsNullOrEmpty(str)){str = "\"" + str + "\"";}return str;}#endregion#region 字符串轉Jsion#endregion#region List轉換成Json/// <summary>/// List轉換成Json/// </summary>public static string ListToJson<T>(IList<T> list){object obj = list[0];return ListToJson<T>(list, obj.GetType().Name);}/// <summary>/// List轉換成Json /// </summary>public static string ListToJson<T>(IList<T> list, string jsonName){StringBuilder Json = new StringBuilder();if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;Json.Append("{\"" + jsonName + "\":[");if (list.Count > 0){for (int i = 0; i < list.Count; i++){T obj = Activator.CreateInstance<T>();PropertyInfo[] pi = obj.GetType().GetProperties();Json.Append("{");for (int j = 0; j < pi.Length; j++){Type type = pi[j].GetValue(list, null).GetType();Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list, null).ToString(), type));if (j < pi.Length - 1){Json.Append(",");}}Json.Append("}");if (i < list.Count - 1){Json.Append(",");}}}Json.Append("]}");return Json.ToString();}#endregion#region 對象轉換為Json/// <summary> /// 對象轉換為Json /// </summary> /// <param name="jsonObject">自定義對象</param> /// <returns>Json字符串</returns> public static string ToJson(object jsonObject){string jsonString = "{";PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();for (int i = 0; i < propertyInfo.Length; i++){object objectValue = propertyInfo.GetGetMethod().Invoke(jsonObject, null);string value = string.Empty;if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan || objectValue is string){value = "'" + objectValue.ToString() + "'";}else{value = objectValue.ToString();}jsonString += "\"" + propertyInfo.Name + "\":" + value + ",";}jsonString = jsonString.Remove(jsonString.LastIndexOf(","));return jsonString + "}";}#endregion#region  DataSet轉換為Json/// <summary> /// DataSet轉換為Json /// </summary> /// <param name="dataSet">DataSet對象</param> /// <returns>Json字符串</returns> public static string ToJson(DataSet dataSet){string jsonString = "{";foreach (DataTable table in dataSet.Tables){jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";}jsonString = jsonString.TrimEnd(',');return jsonString + "}";}#endregion#region Datatable轉換為Json/// <summary> /// Datatable轉換為Json /// </summary> /// <param name="table">Datatable對象</param> /// <returns>Json字符串</returns> public static string ToJson(DataTable dt){StringBuilder jsonString = new StringBuilder();jsonString.Append("[");DataRowCollection drc = dt.Rows;for (int i = 0; i < drc.Count; i++){jsonString.Append("{");for (int j = 0; j < dt.Columns.Count; j++){string strKey = dt.Columns[j].ColumnName;string strValue = drc[j].ToString();Type type = dt.Columns[j].DataType;jsonString.Append("\"" + strKey + "\":");strValue = StringFormat(strValue, type);if (j < dt.Columns.Count - 1){jsonString.Append(strValue + ",");}else{jsonString.Append(strValue);}}jsonString.Append("},");}jsonString.Remove(jsonString.Length - 1, 1);jsonString.Append("]");return jsonString.ToString();}/// <summary>/// DataTable轉換為Json /// </summary>public static string ToJson(DataTable dt, string jsonName){StringBuilder Json = new StringBuilder();if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName;Json.Append("{\"" + jsonName + "\":[");if (dt.Rows.Count > 0){for (int i = 0; i < dt.Rows.Count; i++){Json.Append("{");for (int j = 0; j < dt.Columns.Count; j++){Type type = dt.Rows[j].GetType();Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[j].ToString(), type));if (j < dt.Columns.Count - 1){Json.Append(",");}}Json.Append("}");if (i < dt.Rows.Count - 1){Json.Append(",");}}}Json.Append("]}");return Json.ToString();}#endregion#region DataReader轉換為Json/// <summary> /// DataReader轉換為Json /// </summary> /// <param name="dataReader">DataReader對象</param> /// <returns>Json字符串</returns> public static string ToJson(DbDataReader dataReader){StringBuilder jsonString = new StringBuilder();jsonString.Append("[");while (dataReader.Read()){jsonString.Append("{");for (int i = 0; i < dataReader.FieldCount; i++){Type type = dataReader.GetFieldType(i);string strKey = dataReader.GetName(i);string strValue = dataReader.ToString();jsonString.Append("\"" + strKey + "\":");strValue = StringFormat(strValue, type);if (i < dataReader.FieldCount - 1){jsonString.Append(strValue + ",");}else{jsonString.Append(strValue);}}jsonString.Append("},");}dataReader.Close();jsonString.Remove(jsonString.Length - 1, 1);jsonString.Append("]");return jsonString.ToString();}#endregion}
}

?

轉載于:https://www.cnblogs.com/lizeyan/p/3628643.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377169.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377169.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377169.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

let 只能在嚴格模式下嗎_LET的完整形式是什么?

let 只能在嚴格模式下嗎LET&#xff1a;今天早早離開 (LET: Leaving Early Today) LET is an abbreviation of "Leaving Early Today". LET是“ Leaveing Today Today”的縮寫 。 It is an expression, which is commonly used in the Gmail platform. It is writt…

js 遮罩層 loading 效果

//調用方法 //關閉事件<button οnclickLayerHide()>關閉</button>&#xff0c;在loadDiv(text)中&#xff0c;剔除出來 //調用LayerShow(text)&#xff0c;text為參數&#xff0c;可以寫入想要寫入的提示語 //本方法在調用時會自動生成一個添加到body的div&#x…

centos6.5安裝配置LDAP服務[轉]

centos6.5安裝配置LDAP服務[轉] 安裝之前查一下 1find / -name openldap*centos6.4默認安裝了LDAP&#xff0c;但沒有裝ldap-server和ldap-client 于是yum安裝 1su root2yum install -y openldap openldap-servers openldap-clients不建議編譯源碼包&#xff0c;有依賴比較麻煩…

《MySQL——恢復數據-誤刪行、表、庫》

目錄誤刪行事前預防誤刪行數據方法誤刪表/庫延遲復制備庫事前預防誤刪庫/表方法傳統的架構不能預防誤刪數據&#xff0c;因為主庫的一個drop table命令&#xff0c;會通過binlog傳給所有從庫和級聯從庫&#xff0c;進而導致整個集群的實例都會執行這個命令。 MySQL相關的誤刪除…

python圖例位置_Python | 圖例位置

python圖例位置Legends are one of the key components of data visualization and plotting. Matplotlib can automatically define a position for a legend in addition to this, it allows us to locate it in our required positions. Following is the list of locations…

Freemarker中遍歷List實例

Freemarker中如何遍歷List摘要&#xff1a;在Freemarker應用中經常會遍歷List獲取需要的數據&#xff0c;并對需要的數據進行排序加工后呈現給用戶。那么在Freemarker中如何遍歷List&#xff0c;并對List中數據進行適當的排序呢&#xff1f;通過下文的介紹&#xff0c;相信您一…

工作總結:文件對話框的分類(C++)

原文地址&#xff1a;http://www.jizhuomi.com/software/173.html 文件對話框分為打開文件對話框和保存文件對話框&#xff0c;相信大家在Windows系統中經常見到這兩種文件對話框。例如&#xff0c;很多編輯軟件像記事本等都有“打開”選項&#xff0c;選擇“打開”后會彈出一個…

《MySQL——Innodb改進LRU算法》

Innodb改進LRU.算法&#xff0c;實質上將內存鏈表分成兩段。 靠近頭部的young和靠近末尾的old&#xff0c;取5/12段為分界。 新數據在一定時間內只能在old段的頭部&#xff0c;當在old段保持了一定的時間后被再次訪問才能升級到young。 實質上是分了兩段lru&#xff0c;這樣做的…

nfc/nfc模式_NFC的完整形式是什么?

nfc/nfc模式NFC&#xff1a;沒有進一步評論 (NFC: No Further Comment) NFC is an abbreviation of "No Further Comment". NFC是“沒有進一步評論”的縮寫 。 It is an expression, which is commonly used in messaging or chatting on social media networking s…

dx小記(2)

1.構造一個平截臺體&#xff08;Frustum&#xff09; 最近距離-projMatirx.43/projMatrix.33 projMatrix。33 深度/&#xff08;深度-最近距離&#xff09; projMatrix。44-最近距離*&#xff08;深度/&#xff08;深度-最近距離&#xff09;&#xff09; FrustumMatrix proje…

jQuery: 整理4---創建元素和添加元素

1.創建元素&#xff1a;$("內容") const p "<p>這是一個p標簽</p>" console.log(p)console.log($(p)) 2. 添加元素 2.1 前追加子元素 1. 指定元素.prepend(內容) -> 在指定元素的內部的最前面追加內容&#xff0c;內容可以是字符串、…

Design a high performance cache for multi-threaded environment

如何設計一個支持高并發的高性能緩存庫 不 考慮并發情況下的緩存的設計大家應該都比較清楚&#xff0c;基本上就是用map/hashmap存儲鍵值&#xff0c;然后用雙向鏈表記錄一個LRU來用于緩存的清理。這篇文章 應該是講得很清楚http://timday.bitbucket.org/lru.html。但是考慮到高…

《MySQL——join語句優化tips》

目錄要不要用joinJoin驅動表選擇Multi-Range Read優化Batched Key Access &#xff08;BKA&#xff09;對NLJ進行優化BNL算法性能問題BNL轉BKA要不要用join 1、如果使用的是Index Nested-Loop Join算法&#xff0c;即可以用上被驅動表的索引&#xff0c;可以用 2、如果使用的…

scala中抽象類_Scala中的抽象類

scala中抽象類抽象類 (Abstract Class) In the Scala programming language, abstraction is achieved using abstract class. 在Scala編程語言&#xff0c; 抽象是使用抽象類來實現的。 Abstraction is the process of showing only functionality and hiding the details fr…

不能catch Fatal的exception

Clemens Vasters - Are you catching falling knives?里給了一個判斷C#的exception是不是fatal的代碼&#xff0c;可以參考參考。 public static bool IsFatal(this Exception exception) {while (exception ! null){if (exception as OutOfMemoryException ! null &&…

HDU 2824 The Euler function

篩法計算歐拉函數 #include <iostream> #include <cstdio> using namespace std; const int maxn3000005; long long phi[maxn]; int main(){int i,j,a,b;for(i1;i<maxn;i) phi[i]i;for(i2;i<maxn;i2) phi[i]/2;for(i3;i<maxn;i2)if(phi[i]i){for(ji;j<…

LinkChecker 8.1 發布,網頁鏈接檢查

LinkChecker 8.1 可對檢查時間和最大的 URL 數量進行配置&#xff1b;當使用 HTTP 請求時發送 do-not-track 頭&#xff1b;生成 XML 的 sitemap 用于搜索引擎優化&#xff1b;檢測 URL 長度和重復的頁面內容&#xff1b;修復了很多檢查的 bug。 LinkChecker 是一個網頁鏈接檢查…

c語言語言教程0基礎_C語言基礎

c語言語言教程0基礎Hey, Folks here I am back with my second article on C language. Hope you are through with my previous article C language - History, Popularity reasons, Characteristics, Basic structure etc. In this one, I will cover some fundamental conce…

《MySQL——臨時表》

內存表與臨時表區別 臨時表&#xff0c;一般是人手動創建。 內存表&#xff0c;是mysql自動創建和銷毀的。 內存表&#xff0c;指的是使用Memory引擎的表&#xff0c;建表語法&#xff1a;create table ... engine memeory 表的數據存在內存里&#xff0c;系統重啟后會被清…

android中ActionBar的幾個屬性

actionBar.setHomeButtonEnabled //小于4.0版本的默認值為true的。但是在4.0及其以上是false&#xff0c;該方法的作用&#xff1a;決定左上角的圖標是否可以點擊。沒有向左的小圖標。 true 圖標可以點擊 false 不可以點擊。 actionBar.setDisplayHomeAsUpEnabled(true) //…