0

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.

4

3 回答 3

2

像这样试试

 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; }
}

创建一个对象并设置属性...您将获得所有详细信息,然后将其放入数据表中...

   Copy paste your json string it will generate the class 

http://json2csharp.com/

于 2013-09-27T05:57:50.203 回答
1

用这个,

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);
}

或使用JSON.NET.

string json = JsonConvert.SerializeObject(table, new Serialization.DataTableConverter());
var o = JsonConvert.DeserializeObject<DataTable>(json, new Serialization.DataTableConverter());
于 2013-09-27T05:00:47.090 回答
0

如果它是 Microsoft 的.NET 2.0 的 AJAX 扩展,它会帮助你说服你的老板安装一个库吗?

其中包括System.Web.Script.Serialization.JavascriptSerializer,用于您帖子最后一个链接的第 4 步。

于 2013-09-27T05:29:35.930 回答