将字典列表序列化为可接受的DataTable Ajax对象
本文关键字:DataTable Ajax 对象 可接受 字典 列表 序列化 | 更新日期: 2023-09-27 18:14:04
我有一个web应用程序,其中我正在检索一些数据到引导表,我现在要做的是使用jQuery DataTable
而不是当前,因为它有太多有用的功能。
目前我正在使用OOP方法从服务器端检索数据,其中类对象表示特定表中的数据行,该对象包括存储列名和值的字典。
我现在正在做的是,我正在检索这些类对象,并在List<Item>
中附加每个对象的每个字典,然后使用JavaScriptSerializer
对象序列化该列表,该对象返回以下JSON
格式:
[
{
"slno":"2",
"status_message":"Lights still flashing",
"crm_services_id":"1", "subject_id":"Lights are flashing",
"severity_id":"5",
"user_id":"husain.alhamali",
"status_id":"1"
},
{
"slno":"3",
"status_message":"lights working fine",
"crm_services_id":"2",
"subject_id":"Lights are flashing",
"severity_id":"3",
"user_id":"husain.alhamali",
"status_id":"2"
}
]
当我试图使用这个对象来填充我的DataTable AJAX
我有一个错误说:
无效的JSON响应
我看到了一些有效的JSON
响应的例子,DataTable
可以接受,如下:
{
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011/07/25",
"$170,750"
]
}
现在我的问题是,是否有任何工具或插件,可以重新格式化我的JSON
字符串成一个可接受的格式像上面的一个?
与此HTML:
<table id="example"></table>
这个JS将创建一个表:
var data = [{
"slno": "2",
"status_message": "Lights still flashing",
"crm_services_id": "1",
"subject_id": "Lights are flashing",
"severity_id": "5",
"user_id": "husain.alhamali",
"status_id": "1"
}, {
"slno": "3",
"status_message": "lights working fine",
"crm_services_id": "2",
"subject_id": "Lights are flashing",
"severity_id": "3",
"user_id": "husain.alhamali",
"status_id": "2"
}];
function getColumns(){
for(var i = 0; i < data.length; i++){
let columnsArray = [];
var keys = Object.keys(data[i]);
for(k in Object.keys(data[i])){
if(data[i].hasOwnProperty(keys[k])){
columnsArray.push({
"data":keys[k]
});
}
}
return columnsArray;
}
}
$(document).ready(function() {
var table = $('#example').DataTable({
"columns": getColumns(),
"data": data
});
});
工作的例子。
dataTable需要从ajax响应返回json数据,具有以下键1. 数据
2. 画3.recordsTotal4. recordsFiltered
使用
var data = list.Select(u => u.GetType()
.GetProperties()
.Select(p => p.GetValue(u, null)));
public class User
{
public int userId { get; set; }
public string name { get; set; }
}
public class Programm
{
static void Main()
{
var list = new List<User>();
list.Add(new User
{
userId = 1,
name = "name 1",
});
list.Add(new User
{
userId = 2,
name = "name 2",
});
var data = list.Select(u => u.GetType()
.GetProperties()
.Select(p => p.GetValue(u, null)));
Console.WriteLine(new JavaScriptSerializer().Serialize(new
{
data = data
}));
}
}
结果{
"data" : [
["1", "name 1"],
["2", "name 2"]
]
}