len = models.Count; i len; i++ ){ if ( 0 != i)sb.Append( "

时间:2021-12-12 06:08:23

由于比来项目里面Model类出格多,而我需要编写所有数据交互的接口,传输的格局是json,以前都是通过循环List<T>中的东西向StringBuilder东西中Apped字符串生成json,而这样一来此次项目岂不是得写死人,想了想不能冒这个危害,因此感受写一个通用的Model转json的要领如下:

/// <summary> /// 转换T为json /// </summary> /// <typeparam>类型</typeparam> /// <param>东西</param> /// <returns>json</returns> private string ConvertToJson<T>(T model) { //获取属性调集 PropertyInfo[] properties = model.GetType().GetProperties(); StringBuilder sb = new StringBuilder(); sb.Append("{");   
  
//遍历属性调集 for (int i = 0, len = properties.Length; i < len; i++) {
     if(0!=i)sb.Append(","); sb.AppendFormat(
"\"{0}\":\"{1}\"", properties[i].Name.ToLower(),//属性名作为 键 properties[i].GetValue(model, null).ToString());//属性值作为 值
} sb.Append(
"}"); return sb.ToString(); }

通过泛型可以接收任意自界说类型进行操纵;

完成了这个之后俄然我又发明还是要循环很多List<T>,也很麻烦,,所以爽性再重载一下,既可以直接转Model,也可以直接转List<Model>岂不是越发便利,于是(此处是完整代码):

/// <summary> /// 转换List<T>为json /// </summary> /// <typeparam></typeparam> /// <param></param> /// <returns></returns> private string ConvertToJson<T>(List<T> models) { StringBuilder sb = new StringBuilder(); for (int i = 0, len = models.Count; i < len; i++) { if (0 != i) sb.Append(","); sb.Append(ConvertToJson(models[i])); } return sb.ToString(); } /// <summary> /// 转换T为json /// </summary> /// <typeparam></typeparam> /// <param></param> /// <returns></returns> private string ConvertToJson<T>(T model) { //获取属性调集 PropertyInfo[] properties = model.GetType().GetProperties(); StringBuilder sb = new StringBuilder(); sb.Append("{");//遍历属性调集 for (int i = 0, len = properties.Length; i < len; i++) {
    if(0!=i)sb.Append(","); sb.AppendFormat(
"\"{0}\":\"{1}\"", properties[i].Name.ToLower(),//属性名作为 键 properties[i].GetValue(model, null).ToString());//属性值作为 值
} sb.Append("}"); return sb.ToString(); }

至此完毕,代码中组织json格局效率方面还望有大神提着名贵建议!