Convert datatable to JSON in C#

2019-01-01 00:44发布

  1. I want to get records from database into a DataTable.
  2. Then convert the DataTable into a JSON object.
  3. Return the JSON object to my JavaScript function.

I use this code by calling:

string result = JsonConvert.SerializeObject(DatatableToDictionary(queryResult, "Title"), Newtonsoft.Json.Formatting.Indented);

To convert a DataTable to JSON, it works correctly and return the following:

{
    "1": {
    "viewCount": 703,
    "clickCount": 98
    },
    "2": {
    "viewCount": 509,
    "clickCount": 85
    },
    "3": {
    "viewCount": 578,
    "clickCount": 86
    },
    "4": {
    "viewCount": 737,
    "clickCount": 108
    },
    "5": {
    "viewCount": 769,
    "clickCount": 130
    }
} 

But I would like it to return the following:

{"records":[
{
"Title": 1,
"viewCount": 703,
"clickCount": 98
},
{
"Title": 2,
"viewCount": 509,
"clickCount": 85
},
{
"Title": 3,
"viewCount": 578,
"clickCount": 86
},
{
"Title": 4,
"viewCount": 737,
"clickCount": 108
},
{
"Title": 5,
"viewCount": 769,
"clickCount": 130
}
]} 

How can I do this?

13条回答
柔情千种
2楼-- · 2019-01-01 01:05

I have simple function to convert datatable to json string.

I have used Newtonsoft to generate string. I don't use Newtonsoft to totaly serialize Datatable. Be careful about this.

Maybe this can be useful.

 private string DataTableToJson(DataTable dt) {
  if (dt == null) {
   return "[]";
  };
  if (dt.Rows.Count < 1) {
   return "[]";
  };

  JArray array = new JArray();
  foreach(DataRow dr in dt.Rows) {
   JObject item = new JObject();
   foreach(DataColumn col in dt.Columns) {
    item.Add(col.ColumnName, dr[col.ColumnName]?.ToString());
   }
   array.Add(item);
  }

  return array.ToString(Newtonsoft.Json.Formatting.Indented);
 }
查看更多
查无此人
3楼-- · 2019-01-01 01:09

To access the convert datatable value in Json method follow the below steps:

$.ajax({
        type: "POST",
        url: "/Services.asmx/YourMethodName",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var parsed = $.parseJSON(data.d);
            $.each(parsed, function (i, jsondata) {
            $("#dividtodisplay").append("Title: " + jsondata.title + "<br/>" + "Latitude: " + jsondata.lat);
            });
        },
        error: function (XHR, errStatus, errorThrown) {
            var err = JSON.parse(XHR.responseText);
            errorMessage = err.Message;
            alert(errorMessage);
        }
    });
查看更多
冷夜・残月
4楼-- · 2019-01-01 01:11

With Cinchoo ETL - an open source library, you can export DataTable to JSON easily with few lines of code

StringBuilder sb = new StringBuilder();
string connectionstring = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Northwind;Integrated Security=True";
using (var conn = new SqlConnection(connectionstring))
{
    conn.Open();
    var comm = new SqlCommand("SELECT * FROM Customers", conn);
    SqlDataAdapter adap = new SqlDataAdapter(comm);

    DataTable dt = new DataTable("Customer");
    adap.Fill(dt);

    using (var parser = new ChoJSONWriter(sb))
        parser.Write(dt);
}

Console.WriteLine(sb.ToString());

Output:

{"Customer": [
 {
   "CustomerID": "ALFKI",
   "CompanyName": "Alfreds Futterkiste",
   "ContactName": "Maria Anders",
   "ContactTitle": "Sales Representative",
   "Address": "Obere Str. 57",
   "City": "Berlin",
   "Region": null,
   "PostalCode": "12209",
   "Country": "Germany",
   "Phone": "030-0074321",
   "Fax": "030-0076545"
 },
 {
   "CustomerID": "ANATR",
   "CompanyName": "Ana Trujillo Emparedados y helados",
   "ContactName": "Ana Trujillo",
   "ContactTitle": "Owner",
   "Address": "Avda. de la Constitución 2222",
   "City": "México D.F.",
   "Region": null,
   "PostalCode": "05021",
   "Country": "Mexico",
   "Phone": "(5) 555-4729",
   "Fax": "(5) 555-3745"
 }
]}
查看更多
深知你不懂我心
5楼-- · 2019-01-01 01:12

Convert datatable to JSON using C#.net

 public static object DataTableToJSON(DataTable table)
    {
        var list = new List<Dictionary<string, object>>();

        foreach (DataRow row in table.Rows)
        {
            var dict = new Dictionary<string, object>();

            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = (Convert.ToString(row[col]));
            }
            list.Add(dict);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        return serializer.Serialize(list);
    }
查看更多
孤独总比滥情好
6楼-- · 2019-01-01 01:15

An alternative way without using javascript serializer:

    public static string DataTableToJSON(DataTable Dt)
            {
                string[] StrDc = new string[Dt.Columns.Count];

                string HeadStr = string.Empty;
                for (int i = 0; i < Dt.Columns.Count; i++)
                {

                    StrDc[i] = Dt.Columns[i].Caption;
                    HeadStr += "\"" + StrDc[i] + "\":\"" + StrDc[i] + i.ToString() + "¾" + "\",";

                }

                HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);

                StringBuilder Sb = new StringBuilder();

                Sb.Append("[");

                for (int i = 0; i < Dt.Rows.Count; i++)
                {

                    string TempStr = HeadStr;

                    for (int j = 0; j < Dt.Columns.Count; j++)
                    {

                        TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString().Trim());
                    }
                    //Sb.AppendFormat("{{{0}}},",TempStr);

                    Sb.Append("{"+TempStr + "},");
                }

                Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));

                if(Sb.ToString().Length>0)
                Sb.Append("]");

                return StripControlChars(Sb.ToString());

            }
//To strip control characters:

//A character that does not represent a printable character but //serves to initiate a particular action.

            public static string StripControlChars(string s)
            {
                return Regex.Replace(s, @"[^\x20-\x7F]", "");
            }
查看更多
怪性笑人.
7楼-- · 2019-01-01 01:17

Pass the datable to this method it would return json String.

public DataTable GetTable()
        {
            string str = "Select * from GL_V";
            OracleCommand cmd = new OracleCommand(str, con);
            cmd.CommandType = CommandType.Text;
            DataTable Dt = OracleHelper.GetDataSet(con, cmd).Tables[0];

            return Dt;
        }

        public string DataTableToJSONWithJSONNet(DataTable table)
        {
            string JSONString = string.Empty;
            JSONString = JsonConvert.SerializeObject(table);
            return JSONString;
        }



public static DataSet GetDataSet(OracleConnection con, OracleCommand cmd)
        {
            // create the data set  
            DataSet ds = new DataSet();
            try
            {
                //checking current connection state is open
                if (con.State != ConnectionState.Open)
                    con.Open();

                // create a data adapter to use with the data set
                OracleDataAdapter da = new OracleDataAdapter(cmd);

                // fill the data set
                da.Fill(ds);
            }
            catch (Exception ex)
            {

                throw;
            }
            return ds;
        }
查看更多
登录 后发表回答