DataTable 数据表转成JSON

第一个发送到前台要eval一下.转换成JS的数组

第二个转换成真正的JSON数据


     /// <summary> 
    
/// 将一个数据表转换成一个JSON字符串,在客户端可以直接转换成二维数组。 
    
/// </summary> 
    
/// <param name="source">需要转换的表。</param> 
    
/// <returns></returns> 
    public static string DataTableToJson(DataTable source) 
    { 
        
if (source.Rows.Count == 0
            
return ""
        StringBuilder sb 
= new StringBuilder("["); 
        
foreach (DataRow row in source.Rows) 
        { 
            sb.Append(
"["); 
            
for (int i = 0; i < source.Columns.Count; i++
            { 
                sb.Append(
'"' + row.ToString() + "\","); 
            } 
            sb.Remove(sb.Length 
- 11); 
            sb.Append(
"],"); 
        } 
        sb.Remove(sb.Length 
- 11); 
        sb.Append(
"]"); 
        
return sb.ToString(); 
    }

 

    /// <summary> 
    
/// 反回JSON数据到前台 
    
/// </summary> 
    
/// <param name="dt">数据表</param> 
    
/// <returns>JSON字符串</returns> 
    public string CreateJsonParameters(DataTable dt) 
    { 
        StringBuilder JsonString 
= new StringBuilder(); 
        
//Exception Handling         
        if (dt != null && dt.Rows.Count > 0
        { 
            JsonString.Append(
""); 
            JsonString.Append(
"\"TableInfo\":[ "); 
            
for (int i = 0; i < dt.Rows.Count; i++
            { 
                JsonString.Append(
""); 
                
for (int j = 0; j < dt.Columns.Count; j++
                { 
                    
if (j < dt.Columns.Count - 1
                    { 
                        JsonString.Append(
"\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[j].ToString() + "\","); 
                    } 
                    
else if (j == dt.Columns.Count - 1
                    { 
                        JsonString.Append(
"\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[j].ToString() + "\""); 
                    } 
                } 
                
/**/ 
                
/*end Of String*/ 
                
if (i == dt.Rows.Count - 1
                { 
                    JsonString.Append(
""); 
                } 
                
else 
                { 
                    JsonString.Append(
"}, "); 
                } 
            } 
            JsonString.Append(
"]}"); 
            
return JsonString.ToString(); 
        } 
        
else 
        { 
            
return null
        } 
    }

 

 【转】http://www.cnblogs.com/liuju150/archive/2009/07/10/database-to-JSON.html

posted @ 2009-07-13 09:39  TONYBINLJ  阅读(512)  评论(0编辑  收藏  举报