C# .NET web.api json result get

Anonymous
2022-09-05T09:09:41.25+00:00

I need to create an api and when invoked an endpoint to list the available players on http://localhost:3000/api/player/.

I should get json result like
[
{
"id": 1,
"name": "player name 1",
"position": "defender",
"playerSkills": [
{
"id": 1,
"skill": "defense",
"value": 60,
"playerId": 1
},
{
"id": 2,
"skill": "speed",
"value": 80,
"playerId": 1
}
]
},
{
"id": 2,
"name": "player name 2",
"position": "midfielder",
"playerSkills": [
{
"id": 3,
"skill": "attack",
"value": 20,
"playerId": 2
},
{
"id": 4,
"skill": "speed",
"value": 70,
"playerId": 2
}
]
}
]

I tried the below reference but this gives me output in xml

https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
301 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2022-09-05T14:29:28.457+00:00

    @AgaveJoe

    I added this in global.asax and it started working
    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

    Product[] products = new Product[]
    {
    new Product { Id = 1, Name = "Player1", position="Midfielder" },
    new Product { Id = 2, Name = "Player2",Position="Defender"}

        };  
    
        public IEnumerable<Product> GetAllProducts()  
        {  
            return products;  
        }  
    

    How do I add player skills to return the below json format please note player skills could be an array for a single Player.

    [
    {
    "id": 1,
    "name": "player name 1",
    "position": "defender",
    "playerSkills": [
    {
    "id": 1,
    "skill": "defense",
    "value": 60,
    "playerId": 1
    },
    {
    "id": 2,
    "skill": "speed",
    "value": 80,
    "playerId": 1
    }
    ]
    },
    {
    "id": 2,
    "name": "player name 2",
    "position": "midfielder",
    "playerSkills": [
    {
    "id": 3,
    "skill": "attack",
    "value": 20,
    "playerId": 2
    },
    {
    "id": 4,
    "skill": "speed",
    "value": 70,
    "playerId": 2
    }
    ]
    }
    ]