使用json.net返回一个多维json数组

本文关键字:json 一个 数组 net 返回 使用 | 更新日期: 2023-09-27 18:20:57

我有这个代码:

var all_books = db.Books;
var result = all_books.Select(a => new { a.bookid, a.booktitle, a.bookisbn}).Take(4).ToList();
var jsonData = new {
                sEcho = param.sEcho,
                iTotalRecords = all_assets.Count(),
                iTotalDisplayRecords = all_assets.Count(),
                aaData = result
            };
return Json(jsonData,JsonRequestBehavior.AllowGet);

返回的json格式为:

{"sEcho":null,"iTotalRecords":2764,"iTotalDisplayRecords":2764,"aaData":[{"bookid":"M-711745","booktitle":"20844","bookisbn":"HP LA2205wg"},{"bookid":null,"booktitle":"n/a","bookisbn":"n/a"},{"bookid":"M-710587","booktitle":"20707","bookisbn":"HP LA2205wg"},{"bookid":"735129","booktitle":"21272","bookisbn":"HP LA2205wg"}]}

我想返回一个多维数组。

{"sEcho":null,"iTotalRecords":2764,"iTotalDisplayRecords":2764,"aaData":[["bookid":"M-711745","booktitle":"20844","bookisbn":"HP LA2205wg"],["bookid":null,"booktitle":"n/a","bookisbn":"n/a"],["bookid":"M-710587","booktitle":"20707","bookisbn":"HP LA2205wg"],["bookid":"735129","booktitle":"21272","bookisbn":"HP LA2205wg"]]}

我试过这个代码:

var result = all_books.Select(a => new List<string[]>() { new string[]{ a.bookid, a.booktitle, a.bookisbn }}).Take(4);

但我得到了这个错误:

The array type 'System.String[]' cannot be initialized in a query result. Consider using 'System.Collections.Generic.List`1[System.String]' instead.

我错过了什么?

使用json.net返回一个多维json数组

试试这个:

var result = all_books
    .Select(a => new List<string> { a.bookid, a.booktitle, a.bookisbn })
    .Take(4)
    .ToList();

当你序列化它时,你应该得到以下JSON,我认为这就是你想要的:

{
    "sEcho":null,
    "iTotalRecords":2764,
    "iTotalDisplayRecords":2764,
    "aaData":
    [
        ["M-711745","20844","HP LA2205wg"],
        [null,"n/a","n/a"],
        ["M-710587","HP LA2205wg","20707"],
        ["735129","HP LA2205wg","21272"]
    ]
}