1 /// <summary> 2 /// IDataReader转换为Json 3 /// </summary> 4 /// <param name="dataReader">DataReader对象</param> 5 /// <returns>Json字符串</returns> 6 public static string ToJson(IDataReader dataReader) 7 { 8 try 9 { 10 StringBuilder jsonString = new StringBuilder(); 11 jsonString.Append("["); 12 13 while (dataReader.Read()) 14 { 15 jsonString.Append("{"); 16 for (int i = 0; i < dataReader.FieldCount; i++) 17 { 18 Type type = dataReader.GetFieldType(i); 19 string strKey = dataReader.GetName(i); 20 string strValue = dataReader[i].ToString(); 21 jsonString.Append("\"" + strKey + "\":"); 22 strValue = StringFormat(strValue, type); 23 if (i < dataReader.FieldCount - 1) 24 { 25 jsonString.Append(strValue + ","); 26 } 27 else 28 { 29 jsonString.Append(strValue); 30 } 31 } 32 jsonString.Append("},"); 33 } 34 if (!dataReader.IsClosed) 35 { 36 dataReader.Close(); 37 } 38 jsonString.Remove(jsonString.Length - 1, 1); 39 jsonString.Append("]"); 40 if (jsonString.Length == 1) 41 { 42 return "[]"; 43 } 44 return jsonString.ToString(); 45 } 46 catch (Exception ex) 47 { 48 throw ex; 49 } 50 } 51 /// <summary> 52 /// 格式化字符型、日期型、布尔型 53 /// </summary> 54 /// <param name="str"></param> 55 /// <param name="type"></param> 56 /// <returns></returns> 57 private static string StringFormat(string str, Type type) 58 { 59 if (type != typeof(string) && string.IsNullOrEmpty(str)) 60 { 61 str = "\"" + str + "\""; 62 } 63 else if (type == typeof(string)) 64 { 65 str = String2Json(str); 66 str = "\"" + str + "\""; 67 } 68 else if (type == typeof(DateTime)) 69 { 70 str = "\"" + str + "\""; 71 } 72 else if (type == typeof(bool)) 73 { 74 str = str.ToLower(); 75 } 76 else if (type == typeof(byte[])) 77 { 78 str = "\"" + str + "\""; 79 } 80 else if (type == typeof(Guid)) 81 { 82 str = "\"" + str + "\""; 83 } 84 return str; 85 } 86 /// <summary> 87 /// 过滤特殊字符 88 /// </summary> 89 /// <param name="s"></param> 90 /// <returns></returns> 91 public static string String2Json(String s) 92 { 93 StringBuilder sb = new StringBuilder(); 94 for (int i = 0; i < s.Length; i++) 95 { 96 char c = s.ToCharArray()[i]; 97 switch (c) 98 { 99 case '\"': 100 sb.Append("\\\""); break; 101 case '\\': 102 sb.Append("\\\\"); break; 103 case '/': 104 sb.Append("\\/"); break; 105 case '\b': 106 sb.Append("\\b"); break; 107 case '\f': 108 sb.Append("\\f"); break; 109 case '\n': 110 sb.Append("\\n"); break; 111 case '\r': 112 sb.Append("\\r"); break; 113 case '\t': 114 sb.Append("\\t"); break; 115 case '\v': 116 sb.Append("\\v"); break; 117 case '\0': 118 sb.Append("\\0"); break; 119 default: 120 sb.Append(c); break; 121 } 122 } 123 return sb.ToString(); 124 }
本文来自博客园,作者:旧路人,转载请注明原文链接:https://www.cnblogs.com/snrj/p/17165015.html