Individual JSON data from datatable in c # asp.net webforms

I am currently trying to transfer the cal-heatmap js json file to a project file, with manual data entry it works fine, however I cannot get the converted datatable to json that really is needed, the format that I am currently getting from the below code below

public void ConvertDataTabletoString()
{
    DataTable dtjson = new DataTable();
    con.Open();
    SqlDataAdapter da = new SqlDataAdapter("select Date, count(id) as co from volunteer Group BY Date Order by Date", con);
    da.Fill(dtjson);
    con.Close();
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> row;
    foreach (DataRow dr in dtjson.Rows)
    {
        row = new Dictionary<string, object>();

        foreach (DataColumn col in dtjson.Columns)
        {

                row.Add(col.ColumnName, dr[col]);
        }
        rows.Add(row);
    }

It generates a JSON format like this

{"Date":"2/15/2016","co":8},
{"Date":"2/24/2016","co":2},
{"Date":"2/25/2016","co":1},
{"Date":"2/6/2016","co":1},
{"Date":"2/7/2016","co":4},
{"Date":"2/8/2016","co":8},
{"Date":"3/19/2016","co":17},
{"Date":"3/21/2016","co":1}

But I want the data to be in the following format without column names and multiple brackets

{ 
"2/15/2016": 20,
"2/24/2016": 40
}

I don't mind if you can even go and do it in a text file and not use JSON serialization

+4
source share
1 answer

You have two options.

= > , , , , ( )

[ 
    [row1col1value,row1col2value,row1col3value]
    [row2col1value,row2col2value,row2col3value]
]

,

    List<List<string>> rows = new List<List<string>>();
    foreach (DataRow dr in dtjson.Rows)
    {
        List<string> row = new List<string>();

        foreach (DataColumn col in dtjson.Columns)
        {    
              row.Add(dr[col].toString());
        }
        rows.Add(row);
    }

, , , , , . { "2/15/2016": 20, "2/24/2016": 40 }

    Dictionary<string,object> rows = new Dictionary<string,object>();

    foreach (DataRow dr in dtjson.Rows)
    {   
        rows.[dtjson.col[0].toString()], dr[dtjson.col[1]]);
        rows.Add(row);
    }

: OP

foreach (DataRow drp in dtjso.Rows) 
{
    DateTime dat = Convert.ToDateTime(drp["Date"]);
    int epo = epoch(dat);
    string check = Convert.ToString(drp["co"]);
    string abc = string.Format("\"{0}\": {1},", epo, check);
    sb.Append(abc); 
}
+1

All Articles