2

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.

1 Answer 1

4

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

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.