user1253073
user1253073

Reputation: 404

Create Json in C# from DataTable

I am using the wdcalendar with asp.net. After getting the records from the database I need to return a JSON string back to the page. I have the DataTable which contains the records from the DB but I am not sure how to convert it to this exact format:

{ 
  "end" : "09/29/2013 23:59",
  "error" : null,
  "events" : [ [ 1,
        "test",
        "09/26/2013 08:11",
        "09/26/2013 08:08",
        0,
        0,
        0,
        "1",
        1,
        "loca",
        ""
      ],
      [ 2,
        "test2",
        "09/27/2013 08:11",
        "09/27/2013 08:08",
        0,
        0,
        0,
        "1",
        1,
        "loca",
        ""
      ]
    ],
  "issort" : true,
  "start" : "09/23/2013 00:00"
}

I added a new line to show the different data which contains two rows from the database and then at the end there is additional info appended to the data which is the last line shown above.

I am hoping there is a better way then building the string manually.

Thanks.

Upvotes: 0

Views: 1743

Answers (3)

Aravind
Aravind

Reputation: 1549

Try like this

 public class RootObject
 {
public string end { get; set; }
public object error { get; set; }
public List<List<object>> events { get; set; }
public bool issort { get; set; }
public string start { get; set; }
}

Create a Object and set the properties ... you will get all the details then put it in datatable ...

   Copy paste your json string it will generate the class 

http://json2csharp.com/

Upvotes: 2

Nirmal
Nirmal

Reputation: 934

Would it help you convince your bosses to install a library if it's Microsoft's AJAX extensions for .NET 2.0?

Included in them is System.Web.Script.Serialization.JavascriptSerializer, which is used in Step 4 of the last link in your post.

Upvotes: 0

Manish Sharma
Manish Sharma

Reputation: 2426

use this,

public string GetJson(DataTable dt)
{
    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 = null;

    foreach (DataRow dr in dt.Rows)
    {
        row = new Dictionary<string, object>();
        foreach (DataColumn col in dt.Columns)
        {
            row.Add(col.ColumnName.Trim(), dr[col]);
        }
        rows.Add(row);
    }
    return serializer.Serialize(rows);
}

or using JSON.NET.

string json = JsonConvert.SerializeObject(table, new Serialization.DataTableConverter());
var o = JsonConvert.DeserializeObject<DataTable>(json, new Serialization.DataTableConverter());

Upvotes: 1

Related Questions