M vc3+ExtJs 数据格式转换(泛型集合转换为Json类型)

直接上代码吧,代码可以说明一切!

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Text;

using System.Reflection;

namespace ProjectManageSys.Extension

{  

   public static class ConvertData     {      

   /// <summary>    

     /// 数据源转换为Json格式   

      /// </summary>    

     /// <typeparam name="TEntity">实体</typeparam>

        /// <param name="source">数据源</param>    

     /// <param name="flag">标记(“0”只显示List:'[{},{}]'"1"显示count,+List:{count:'',list:[{},{},{}]})</param>

        /// <returns>字符窜</returns>   

 public static String ConvertToJson<TEntity>(this IQueryable<TEntity> source, string flag) where TEntity : class     

    {      

       if (source == null && !source.Any())       

      {          

       return string.Empty;    

         }           

  StringBuilder builder = new StringBuilder();         

    if (flag.Equals("1"))     

        {             

    builder.Append("{");           

      builder.AppendFormat("count:{0},list:[", source.Count());        

     }            

if (flag.Equals("0"))        

     {               

  builder.Append("[");   

          }     

        foreach (var obj in source)  

           {          

       builder.Append("{");        

         PropertyInfo[] infos = obj.GetType().GetProperties();   

              foreach (var item in infos)           

      {                 

    builder.Append(item.Name);         

            builder.Append(":");       

              if (item.GetValue(obj, null) == null || item.GetValue(obj, null).Equals(""))  

                   {                   

      builder.Append("''");        

             }                

     else              

       {                    

     builder.Append("'" + item.GetValue(obj, null) + "'");         

            }             

        builder.Append(",");           

      }            

     builder.Remove(builder.Length - 1, 1);        

         builder.Append("}");           

      builder.Append(",");           

  }           

  builder.Remove(builder.Length - 1, 1);       

      builder.Append("]");         

    if (flag.Equals("1"))        

     {           

      builder.Append("}");       

      }       

      return builder.ToString();      

   }

    }

}

此方法有不足的地方就是没有处理存在外键关系的数据,所以请大牛们指点!

原文地址:https://www.cnblogs.com/a546558309/p/2572731.html