Convert datatable to Json

Asked

Viewed 15 times

-1

Datatable data can be stored in JSON?

I have this code:

  public List<AgendaModel> MostrarTodosCalendar()
    {
        List<AgendaModel> lista = new List<AgendaModel>();
        AgendaModel item;
        DAL objDAL = new DAL();
        string sql = "SELECT id, title, start, end, AllDay, Color, TextColor FROM agenda";
        DataTable dt = objDAL.RetDataTable(sql);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            item = new AgendaModel
            {

                Id = dt.Rows[i]["Id"].ToString(),
                Title = dt.Rows[i]["Title"].ToString(),
                Start = dt.Rows[i]["Start"].ToString(),
                End = dt.Rows[i]["End"].ToString(),
                //AllDay = dt.Rows[i]["Allday"].ToString(),
                Color = dt.Rows[i]["Color"].ToString(),
                TextColor = dt.Rows[i]["TextColor"].ToString()

            };

            lista.Add(item);
        }

        return lista;
    }

1 answer

0

I use this function I found in community in English

public string DataTableToJsonObj(DataTable dt)
{
    DataSet ds = new DataSet();
    ds.Merge(dt);
    StringBuilder JsonString = new StringBuilder();
    if (ds != null && ds.Tables[0].Rows.Count > 0)
    {
        JsonString.Append("[");
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            JsonString.Append("{");
            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
            {
                if (j < ds.Tables[0].Columns.Count - 1)
                {
                    JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\",");
                }
                else if (j == ds.Tables[0].Columns.Count - 1)
                {
                    JsonString.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\"");
                }
            }
            if (i == ds.Tables[0].Rows.Count - 1)
            {
                JsonString.Append("}");
            }
            else
            {
                JsonString.Append("},");
            }
        }
        JsonString.Append("]");
        return JsonString.ToString();
    }
    else
    {
        return null;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.