1

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?

1 Answer 1

2

have you tried:

// this will return a List<string>
var result = books.Select(p => p.Author).ToList(); 
return Json(new { authors = result });
Sign up to request clarification or add additional context in comments.

1 Comment

Correct. You need a string list named authors, rather than a list of anonymous objects with Author properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.