romiem
romiem

Reputation: 8970

How to convert a list of anonymous object to string array using linq for return using Json Result in ASP.NET MVC

I currently have a list of a book object as follows:

public class Book()
{
    public int BookId { get; set; }
    public string Name { get; set; }
    public string Author { get; set; }
}

List<Book> books = BookRepository.SelectAll();

I would like to return a string list/array of Authors for return via a Json Result in my action method. At the moment I have done:

var result = books.Select(p => new { p.Author }).ToList();
return Json(new { authors = result });

However, inspecting the result gives the following JSON:

{
    authors: [
        { Author: "John" },
        { Author: "Gary" },
        { Author: "Bill" },
        { Author: "Ray" }
    ]
}

However, I do not want each Author as a seperate object in the JSON. I would like the result as:

{
    authors: ["John", "Gary", "Bill", "Ray"]
}

How do I go about achieving this?

Upvotes: 1

Views: 2099

Answers (1)

John Boker
John Boker

Reputation: 83729

have you tried:

// this will return a List<string>
var result = books.Select(p => p.Author).ToList(); 
return Json(new { authors = result });

Upvotes: 2

Related Questions