Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IQueryable generic to JSON

I'm producing a projection via:

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

In my razor page I need to use:

    var booksArray = [{
        @(json)
    }];

such that the resulting array looks like:

label: 'c++',
value: 'c++'
}, {
label: 'java',
value: 'java'
}, {
label: 'php',
value: 'php'
}, {
label: 'coldfusion',
value: 'coldfusion'
}

I've come very very close from a couple different approaches - I can get a string that looks correct on the server side but when rendered to the page itself, all the ' marks become ' .

But focusing on achieving this via JSON.net...

The most likely approach seems like it should be:

var json = JsonConvert.ToString(query);

but that tosses:

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.

What's the correct JSON.net syntax?

thx

like image 443
justSteve Avatar asked Aug 26 '12 13:08

justSteve


1 Answers

You need a combination of .ToArray() and Html.Raw()

ToArray() to evaluate the query and make JsonConvert happy

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

var json = JsonConvert.SerializeObject(query.ToArray());

Note: you need to use JsonConvert.SerializeObject if you want to serialize complex types. JsonConvert.ToString is used to convert simple types like bool, guid, int, uri etc.

And in your view Html.Raw to not html encode the JSON:

var booksArray = @(Html.Raw(json))
like image 181
nemesv Avatar answered Sep 21 '22 02:09

nemesv