【发布时间】:2017-04-07 17:43:52
【问题描述】:
默认情况下,DataTables Ajax 期望 JSON 数据是一个数组。
使用JSON.Net 是否可以通过属性/设置将集合序列化为数组数组而不是对象数组,或者是否必须通过自定义JsonConverter 来完成。我要序列化的对象如下:
public class DeviceIndex
{
public int Id { get; set; }
[Display(Name = "Asset Tag")]
public string AssetTag { get; set; }
[Display(Name = "Lease End")]
[DataType(DataType.Date)]
public DateTime LeaseEndDate { get; set; }
public string Type { get; set; }
[Display(Name = "Operating System")]
public string OperatingSystem { get; set; }
public string Model { get; set; }
}
而我的控制器动作如下:
public IActionResult IndexJson()
{
var model = _db.Devices.Select(d => new DeviceIndex { ... }).ToList();
return Content(JsonConvert.SerializeObject(new { data = model }), "application/json");
}
哪个输出 JSON:
{
"data": [
{
"Id": 1649,
...
},
{
"Id": 703,
...
}
]
}
虽然我想要的结果如下:
{
"data": [
[
"1649",
...
],
[
"703",
...
]
]
}
我以为我可以为我的集合使用 JsonArray 属性,但它看起来不会改变输出。
[JsonArray]
public class DevicesIndex: IEnumerable<DeviceIndex>
{
List<DeviceIndex> devices;
public IEnumerator<DeviceIndex> GetEnumerator()
{
return devices.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
【问题讨论】:
-
所以你需要json看起来像你的第一个json,一个数组对象的数组?如果是,您必须序列化 List
- > 这将是 json 作为数组字符串的数组。
标签: c# arrays json datatables json.net