将IQueryable泛型转换为JSON

jus*_*eve 7 asp.net-mvc json json.net razor

我通过以下方式制作投影:

var query = from book in books
    select new
    {
        label = book.Title,
        value = book.ID
    };
Run Code Online (Sandbox Code Playgroud)

在我的剃刀页面中,我需要使用:

    var booksArray = [{
        @(json)
    }];
Run Code Online (Sandbox Code Playgroud)

这样得到的数组看起来像:

label: 'c++',
value: 'c++'
}, {
label: 'java',
value: 'java'
}, {
label: 'php',
value: 'php'
}, {
label: 'coldfusion',
value: 'coldfusion'
}
Run Code Online (Sandbox Code Playgroud)

我从几种不同的方法非常接近 - 我可以得到一个在服务器端看起来正确的字符串但是当呈现给页面本身时,所有的'标记都变成了'.

但专注于通过JSON.net实现这一目标......

最可能的方法似乎应该是:

var json = JsonConvert.ToString(query);
Run Code Online (Sandbox Code Playgroud)

但那扔了:

Unsupported type: System.Linq.Enumerable+WhereSelectListIterator`2[Project.Entity.Book,<>f__AnonymousType3`2[System.String,System.Int32]]. Use the JsonSerializer class to get the object's JSON representation.
Run Code Online (Sandbox Code Playgroud)

什么是正确的JSON.net语法?

谢谢

nem*_*esv 11

你需要.ToArray()Html.Raw()的组合

ToArray()评估查询并使JsonConvert快乐

var query = from book in books
    select new
    {
        label = book.Title,
        value = book.ID
    };

var json = JsonConvert.SerializeObject(query.ToArray());
Run Code Online (Sandbox Code Playgroud)

注意:JsonConvert.SerializeObject如果要序列化复杂类型,则需要使用.JsonConvert.ToString用于转换简单类型,如bool,guid,int,uri等.

并且在您看来Html.Raw不对html编码JSON:

var booksArray = @(Html.Raw(json))
Run Code Online (Sandbox Code Playgroud)