首页 > 代码库 > C# Entity To Json

C# Entity To Json

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using System.Web.Script.Serialization;

/// <summary>
/// Summary description for Common
/// </summary>
public class Common
{
    private static JavaScriptSerializer jss;
    public static string DataTableToJson(DataTable dt)
    {
        if (dt == null || dt.Rows.Count == 0)
            return "";

        int length = dt.Rows.Count;

        StringBuilder strbuild = new StringBuilder();
        strbuild.Append("[");//转换成多个model的形式 
        for (int i = 0; i < length; i++)
        {
            strbuild.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                strbuild.Append("\"");
                strbuild.Append(dt.Columns[j].ColumnName);
                strbuild.Append("\":\"");
                strbuild.Append(dt.Rows[i][j].ToString());
                strbuild.Append("\",");
            }
            strbuild.Remove(strbuild.Length - 1, 1);
            strbuild.Append("},");
        }
        strbuild.Remove(strbuild.Length - 1, 1);
        strbuild.Append("]");
        return strbuild.ToString();
    }

    public static string EntityToJson(object obj)
    {
        if (null == jss)
            jss = new JavaScriptSerializer();

        return jss.Serialize(obj);
    }
}

 

C# Entity To Json