johnny
johnny

Reputation: 19735

How do I format a JSON result in ASP.NET Core MVC Web API?

Web API will return JSON automatically, but what if I want it in a different layout. For example, if Web API returns,

[
    {
        "patron": 9,
        "last_name": "Smith",
        "book": {
            "book_id": 1,
            "patron": 9
        }
    },

    {
        "patron": 9,
        "last_name": "Smith",
        "book": {
            "book_id": 2,
            "patron": 9
        }
    },
    {
        "patron": 9,
        "last_name": "Smith",
        "book": {
            "book_id": 3,
            "patron": 9
        }
    }
]

but I want,

[
    {
        "patron": 9,
        "last_name": "Smith",
        "books": [
         {
            "book_id": 1,
            "patron": 9
         },
        {
            "book_id": 2,
            "patron": 9
        },
        {
            "book_id": 3,
            "patron": 9
        }

        ]
    }
]

Is there a way to do this without handwriting my JSON result? I really don't wan to do that.

Upvotes: 2

Views: 300

Answers (1)

davidmdem
davidmdem

Reputation: 3823

The model you are returning needs an IEnumerable type for books.

Currently, the shape of your .NET model/JSON is:

public class Patron
{
    public int patron { get; set; }
    public int book_id { get; set; }
    public Book book { get; set; }
}

While the output you describe looks like this:

public class Patron
{
    public int patron { get; set; }
    public int book_id { get; set; }
    public IEnumerable<Book> books { get; set; }
}

Upvotes: 4

Related Questions