C#中的DataSet、string、DataTable、对象转换成Json的实现代码
C#中对象,字符串,dataTable、DataReader、DataSet,对象集合转换成Json字符串方法。
publicclassConvertJson { #region私有方法 ///<summary> ///过滤特殊字符 ///</summary> ///<paramname="s">字符串</param> ///<returns>json字符串</returns> privatestaticstringString2Json(Strings) { StringBuildersb=newStringBuilder(); for(inti=0;i<s.Length;i++) { charc=s.ToCharArray()[i]; 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; } } returnsb.ToString(); } ///<summary> ///格式化字符型、日期型、布尔型 ///</summary> ///<paramname="str"></param> ///<paramname="type"></param> ///<returns></returns> privatestaticstringStringFormat(stringstr,Typetype) { if(type==typeof(string)) { str=String2Json(str); str="\""+str+"\""; } elseif(type==typeof(DateTime)) { str="\""+str+"\""; } elseif(type==typeof(bool)) { str=str.ToLower(); } elseif(type!=typeof(string)&&string.IsNullOrEmpty(str)) { str="\""+str+"\""; } returnstr; } #endregion #regionlist转换成JSON ///<summary> ///list转换为Json ///</summary> ///<typeparamname="T"></typeparam> ///<paramname="list"></param> ///<returns></returns> publicstaticstringListToJson<T>(IList<T>list) { objectobj=list[0]; returnListToJson<T>(list,obj.GetType().Name); } ///<summary> ///list转换为json ///</summary> ///<typeparamname="T1"></typeparam> ///<paramname="list"></param> ///<paramname="p"></param> ///<returns></returns> privatestaticstringListToJson<T>(IList<T>list,stringJsonName) { StringBuilderJson=newStringBuilder(); if(string.IsNullOrEmpty(JsonName)) JsonName=list[0].GetType().Name; Json.Append("{\""+JsonName+"\":["); if(list.Count>0) { for(inti=0;i<list.Count;i++) { Tobj=Activator.CreateInstance<T>(); PropertyInfo[]pi=obj.GetType().GetProperties(); Json.Append("{"); for(intj=0;j<pi.Length;j++) { Typetype=pi[j].GetValue(list[i],null).GetType(); Json.Append("\""+pi[j].Name.ToString()+"\":"+StringFormat(pi[j].GetValue(list[i],null).ToString(),type)); if(j<pi.Length-1) { Json.Append(","); } } Json.Append("}"); if(i<list.Count-1) { Json.Append(","); } } } Json.Append("]}"); returnJson.ToString(); } #endregion #region对象转换为Json ///<summary> ///对象转换为json ///</summary> ///<paramname="jsonObject">json对象</param> ///<returns>json字符串</returns> publicstaticstringToJson(objectjsonObject) { stringjsonString="{"; PropertyInfo[]propertyInfo=jsonObject.GetType().GetProperties(); for(inti=0;i<propertyInfo.Length;i++) { objectobjectValue=propertyInfo[i].GetGetMethod().Invoke(jsonObject,null); stringvalue=string.Empty; if(objectValueisDateTime||objectValueisGuid||objectValueisTimeSpan) { value="'"+objectValue.ToString()+"'"; } elseif(objectValueisstring) { value="'"+ToJson(objectValue.ToString())+"'"; } elseif(objectValueisIEnumerable) { value=ToJson((IEnumerable)objectValue); } else { value=ToJson(objectValue.ToString()); } jsonString+="\""+ToJson(propertyInfo[i].Name)+"\":"+value+","; } jsonString.Remove(jsonString.Length-1,jsonString.Length); returnjsonString+"}"; } #endregion #region对象集合转换为json ///<summary> ///对象集合转换为json ///</summary> ///<paramname="array">对象集合</param> ///<returns>json字符串</returns> publicstaticstringToJson(IEnumerablearray) { stringjsonString="{"; foreach(objectiteminarray) { jsonString+=ToJson(item)+","; } jsonString.Remove(jsonString.Length-1,jsonString.Length); returnjsonString+"]"; } #endregion #region普通集合转换Json ///<summary> ///普通集合转换Json ///</summary> ///<paramname="array">集合对象</param> ///<returns>Json字符串</returns> publicstaticstringToArrayString(IEnumerablearray) { stringjsonString="["; foreach(objectiteminarray) { jsonString=ToJson(item.ToString())+","; } jsonString.Remove(jsonString.Length-1,jsonString.Length); returnjsonString+"]"; } #endregion #regionDataSet转换为Json ///<summary> ///DataSet转换为Json ///</summary> ///<paramname="dataSet">DataSet对象</param> ///<returns>Json字符串</returns> publicstaticstringToJson(DataSetdataSet) { stringjsonString="{"; foreach(DataTabletableindataSet.Tables) { jsonString+="\""+table.TableName+"\":"+ToJson(table)+","; } jsonString=jsonString.TrimEnd(','); returnjsonString+"}"; } #endregion #regionDatatable转换为Json ///<summary> ///Datatable转换为Json ///</summary> ///<paramname="table">Datatable对象</param> ///<returns>Json字符串</returns> publicstaticstringToJson(DataTabledt) { StringBuilderjsonString=newStringBuilder(); jsonString.Append("["); DataRowCollectiondrc=dt.Rows; for(inti=0;i<drc.Count;i++) { jsonString.Append("{"); for(intj=0;j<dt.Columns.Count;j++) { stringstrKey=dt.Columns[j].ColumnName; stringstrValue=drc[i][j].ToString(); Typetype=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("]"); returnjsonString.ToString(); } ///<summary> ///DataTable转换为Json ///</summary> publicstaticstringToJson(DataTabledt,stringjsonName) { StringBuilderJson=newStringBuilder(); if(string.IsNullOrEmpty(jsonName)) jsonName=dt.TableName; Json.Append("{\""+jsonName+"\":["); if(dt.Rows.Count>0) { for(inti=0;i<dt.Rows.Count;i++) { Json.Append("{"); for(intj=0;j<dt.Columns.Count;j++) { Typetype=dt.Rows[i][j].GetType(); Json.Append("\""+dt.Columns[j].ColumnName.ToString()+"\":"+StringFormat(dt.Rows[i][j].ToString(),type)); if(j<dt.Columns.Count-1) { Json.Append(","); } } Json.Append("}"); if(i<dt.Rows.Count-1) { Json.Append(","); } } } Json.Append("]}"); returnJson.ToString(); } #endregion #regionDataReader转换为Json ///<summary> ///DataReader转换为Json ///</summary> ///<paramname="dataReader">DataReader对象</param> ///<returns>Json字符串</returns> publicstaticstringToJson(DbDataReaderdataReader) { StringBuilderjsonString=newStringBuilder(); jsonString.Append("["); while(dataReader.Read()) { jsonString.Append("{"); for(inti=0;i<dataReader.FieldCount;i++) { Typetype=dataReader.GetFieldType(i); stringstrKey=dataReader.GetName(i); stringstrValue=dataReader[i].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("]"); returnjsonString.ToString(); } #endregion }