C# JSON格式化转换辅助类 ConvertJson
可能我们用惯了Newtonsoft.Json.dll等第三方的类库来实现序列化等类似的操作,但是有时只是简单的用一下,感觉没必要那么费事,所谓杀鸡焉用牛刀,自制个小刀即可。
代码分享给大家,如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Data; usingSystem.Reflection; usingSystem.Collections; usingSystem.Data.Common; publicclassConvertJson { #region私有方法 ///<summary> ///过滤特殊字符 ///</summary> 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> 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> publicstaticstringListToJson<T>(IList<T>list) { objectobj=list[0]; returnListToJson<T>(list,obj.GetType().Name); } ///<summary> ///List转换成Json ///</summary> publicstaticstringListToJson<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">对象</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 }