• 目前为止用过的最好的Json互转工具类ConvertJson


      1 /// <summary>
      2     ///ConvertJson 的摘要说明
      3     /// </summary>
      4     public class ConvertJson
      5     {
      6         #region 私有方法
      7         /// <summary>
      8         /// 过滤特殊字符
      9         /// </summary>
     10         /// <param name="s">字符串</param>
     11         /// <returns>json字符串</returns>
     12         private static string String2Json(String s)
     13         {
     14             StringBuilder sb = new StringBuilder();
     15             for (int i = 0; i < s.Length; i++)
     16             {
     17                 char c = s.ToCharArray()[i];
     18                 switch (c)
     19                 {
     20                     case '"':
     21                         sb.Append("\""); break;
     22                     case '\':
     23                         sb.Append("\\"); break;
     24                     case '/':
     25                         sb.Append("\/"); break;
     26                     case '':
     27                         sb.Append("\b"); break;
     28                     case 'f':
     29                         sb.Append("\f"); break;
     30                     case '
    ':
     31                         sb.Append("\n"); break;
     32                     case '
    ':
     33                         sb.Append("\r"); break;
     34                     case '	':
     35                         sb.Append("\t"); break;
     36                     default:
     37                         sb.Append(c); break;
     38                 }
     39             }
     40             return sb.ToString();
     41         }
     42         /// <summary>
     43         /// 格式化字符型、日期型、布尔型
     44         /// </summary>
     45         /// <param name="str"></param>
     46         /// <param name="type"></param>
     47         /// <returns></returns>
     48         private static string StringFormat(string str, Type type)
     49         {
     50             if (type == typeof(string))
     51             {
     52                 str = String2Json(str);
     53                 str = """ + str + """;
     54             }
     55             else if (type == typeof(DateTime))
     56             {
     57                 str = """ + str + """;
     58             }
     59             else if (type == typeof(bool))
     60             {
     61                 if (str != "")
     62                 {
     63                     str = str.ToLower();
     64                 }
     65                 else
     66                 {
     67                     str = """ + str + """;
     68                 }
     69             }
     70             else if (type != typeof(string) && string.IsNullOrEmpty(str))
     71             {
     72                 str = """ + str + """;
     73             }
     74             return str;
     75         }
     76 
     77         #endregion
     78 
     79         #region list转换成JSON
     80         /// <summary>
     81         /// list转换为Json
     82         /// </summary>
     83         /// <typeparam name="T"></typeparam>
     84         /// <param name="list"></param>
     85         /// <returns></returns>
     86         public static string ListToJson<T>(IList<T> list)
     87         {
     88             object obj = list[0];
     89             return ListToJson<T>(list, obj.GetType().Name);
     90         }
     91         /// <summary>
     92         /// list转换为json
     93         /// </summary>
     94         /// <typeparam name="T1"></typeparam>
     95         /// <param name="list"></param>
     96         /// <param name="p"></param>
     97         /// <returns></returns>
     98         private static string ListToJson<T>(IList<T> list, string JsonName)
     99         {
    100             StringBuilder Json = new StringBuilder();
    101             if (string.IsNullOrEmpty(JsonName))
    102                 JsonName = list[0].GetType().Name;
    103             Json.Append("{"" + JsonName + "":[");
    104             if (list.Count > 0)
    105             {
    106                 for (int i = 0; i < list.Count; i++)
    107                 {
    108                     T obj = Activator.CreateInstance<T>();
    109                     PropertyInfo[] pi = obj.GetType().GetProperties();
    110                     Json.Append("{");
    111                     for (int j = 0; j < pi.Length; j++)
    112                     {
    113                         Type type = pi[j].GetValue(list[i], null).GetType();
    114                         Json.Append(""" + pi[j].Name.ToString() + "":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
    115                         if (j < pi.Length - 1)
    116                         {
    117                             Json.Append(",");
    118                         }
    119                     }
    120                     Json.Append("}");
    121                     if (i < list.Count - 1)
    122                     {
    123                         Json.Append(",");
    124                     }
    125                 }
    126             }
    127             Json.Append("]}");
    128             return Json.ToString();
    129         }
    130         #endregion
    131 
    132         #region 对象转换为Json
    133         /// <summary>
    134         /// 对象转换为json
    135         /// </summary>
    136         /// <param name="jsonObject">json对象</param>
    137         /// <returns>json字符串</returns>
    138         public static string ToJson(object jsonObject)
    139         {
    140             string jsonString = "{";
    141             PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
    142             for (int i = 0; i < propertyInfo.Length; i++)
    143             {
    144                 object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
    145                 string value = string.Empty;
    146                 if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
    147                 {
    148                     value = "'" + objectValue.ToString() + "'";
    149                 }
    150                 else if (objectValue is string)
    151                 {
    152                     value = "'" + ToJson(objectValue.ToString()) + "'";
    153                 }
    154                 else if (objectValue is IEnumerable)
    155                 {
    156                     value = ToJson((IEnumerable)objectValue);
    157                 }
    158                 else
    159                 {
    160                     value = ToJson(objectValue.ToString());
    161                 }
    162                 jsonString += """ + ToJson(propertyInfo[i].Name) + "":" + value + ",";
    163             }
    164             jsonString.Remove(jsonString.Length - 1, jsonString.Length);
    165             return jsonString + "}";
    166         }
    167 
    168         #endregion
    169 
    170         #region 对象集合转换为json
    171         /// <summary>
    172         /// 对象集合转换为json
    173         /// </summary>
    174         /// <param name="array">对象集合</param>
    175         /// <returns>json字符串</returns>
    176         public static string ToJson(IEnumerable array)
    177         {
    178             string jsonString = "{";
    179             foreach (object item in array)
    180             {
    181                 jsonString += ToJson(item) + ",";
    182             }
    183             jsonString.Remove(jsonString.Length - 1, jsonString.Length);
    184             return jsonString + "]";
    185         }
    186         #endregion
    187 
    188         #region 普通集合转换Json
    189         /// <summary>    
    190         /// 普通集合转换Json   
    191         /// </summary>   
    192         /// <param name="array">集合对象</param> 
    193         /// <returns>Json字符串</returns>  
    194         public static string ToArrayString(IEnumerable array)
    195         {
    196             string jsonString = "[";
    197             foreach (object item in array)
    198             {
    199                 jsonString = ToJson(item.ToString()) + ",";
    200             }
    201             jsonString.Remove(jsonString.Length - 1, jsonString.Length);
    202             return jsonString + "]";
    203         }
    204         #endregion
    205 
    206         #region  DataSet转换为Json
    207         /// <summary>    
    208         /// DataSet转换为Json   
    209         /// </summary>    
    210         /// <param name="dataSet">DataSet对象</param>   
    211         /// <returns>Json字符串</returns>    
    212         public static string ToJson(DataSet dataSet)
    213         {
    214             string jsonString = "{";
    215             foreach (DataTable table in dataSet.Tables)
    216             {
    217                 jsonString += """ + table.TableName + "":" + ToJson(table) + ",";
    218             }
    219             jsonString = jsonString.TrimEnd(',');
    220             return jsonString + "}";
    221         }
    222         #endregion
    223 
    224         #region Datatable转换为Json
    225         /// <summary>     
    226         /// Datatable转换为Json     
    227         /// </summary>    
    228         /// <param name="table">Datatable对象</param>     
    229         /// <returns>Json字符串</returns>     
    230         public static string ToJson(DataTable dt)
    231         {
    232             StringBuilder jsonString = new StringBuilder();
    233             jsonString.Append("[");
    234             DataRowCollection drc = dt.Rows;
    235             for (int i = 0; i < drc.Count; i++)
    236             {
    237                 jsonString.Append("{");
    238                 for (int j = 0; j < dt.Columns.Count; j++)
    239                 {
    240                     string strKey = dt.Columns[j].ColumnName;
    241                     string strValue = drc[i][j].ToString();
    242                     Type type = dt.Columns[j].DataType;
    243                     jsonString.Append(""" + strKey + "":");
    244                     strValue = StringFormat(strValue, type);
    245                     if (j < dt.Columns.Count - 1)
    246                     {
    247                         jsonString.Append(strValue + ",");
    248                     }
    249                     else
    250                     {
    251                         jsonString.Append(strValue);
    252                     }
    253                 }
    254                 jsonString.Append("},");
    255             }
    256             jsonString.Remove(jsonString.Length - 1, 1);
    257             jsonString.Append("]");
    258             return jsonString.ToString();
    259         }
    260         /// <summary>    
    261         /// DataTable转换为Json     
    262         /// </summary>    
    263         public static string ToJson(DataTable dt, string jsonName)
    264         {
    265             StringBuilder Json = new StringBuilder();
    266             if (string.IsNullOrEmpty(jsonName))
    267                 jsonName = dt.TableName;
    268             Json.Append("{"" + jsonName + "":[");
    269             if (dt.Rows.Count > 0)
    270             {
    271                 for (int i = 0; i < dt.Rows.Count; i++)
    272                 {
    273                     Json.Append("{");
    274                     for (int j = 0; j < dt.Columns.Count; j++)
    275                     {
    276                         Type type = dt.Rows[i][j].GetType();
    277                         Json.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + StringFormat(dt.Rows[i][j].ToString(), type));
    278                         if (j < dt.Columns.Count - 1)
    279                         {
    280                             Json.Append(",");
    281                         }
    282                     }
    283                     Json.Append("}");
    284                     if (i < dt.Rows.Count - 1)
    285                     {
    286                         Json.Append(",");
    287                     }
    288                 }
    289             }
    290             Json.Append("]}");
    291             return Json.ToString();
    292         }
    293 
    294         #endregion
    295 
    296         #region DataReader转换为Json
    297         /// <summary>     
    298         /// DataReader转换为Json     
    299         /// </summary>     
    300         /// <param name="dataReader">DataReader对象</param>     
    301         /// <returns>Json字符串</returns>  
    302         public static string ToJson(DbDataReader dataReader)
    303         {
    304             StringBuilder jsonString = new StringBuilder();
    305             jsonString.Append("[");
    306             while (dataReader.Read())
    307             {
    308                 jsonString.Append("{");
    309                 for (int i = 0; i < dataReader.FieldCount; i++)
    310                 {
    311                     Type type = dataReader.GetFieldType(i);
    312                     string strKey = dataReader.GetName(i);
    313                     string strValue = dataReader[i].ToString();
    314                     jsonString.Append(""" + strKey + "":");
    315                     strValue = StringFormat(strValue, type);
    316                     if (i < dataReader.FieldCount - 1)
    317                     {
    318                         jsonString.Append(strValue + ",");
    319                     }
    320                     else
    321                     {
    322                         jsonString.Append(strValue);
    323                     }
    324                 }
    325                 jsonString.Append("},");
    326             }
    327             dataReader.Close();
    328             jsonString.Remove(jsonString.Length - 1, 1);
    329             jsonString.Append("]");
    330             return jsonString.ToString();
    331         }
    332         #endregion
    333     }
  • 相关阅读:
    阿里巴巴2015年校招笔试附加题
    hadoop eclipse插件生成
    DevExpress控件的安装及画图控件的使用
    计算二进制数的0的个数
    Docker初探
    AppStore App申请审核加速
    _DataStructure_C_Impl:LinkListBasedSort
    rman数据库恢复;关键/非重要文件、影像副本、控制文件、还原点、非归档、增量、新数据库、灾难性回复
    RenderScript on LLVM笔记
    Oracle数据库备份恢复,巡检须要关注的对象设置以及相关恢复概述
  • 原文地址:https://www.cnblogs.com/moweiran/p/4053424.html
Copyright © 2020-2023  润新知