Convert Object List to JSON in ASP.NET Core Web API

This project will demonstrate how to Convert Object List to JSON in ASP.NET Core Web API

  • LearnASPNETCoreWebAPIWithRealApps
    • Controllers
      • ProductController.cs
    • Models
      • Product.cs
    • Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LearnASPNETCoreWebAPIWithRealApps.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using LearnASPNETCoreWebAPIWithRealApps.Models;

namespace LearnASPNETCoreWebAPIWithRealApps.Controllers
{
    [Route("api/product")]
    public class ProductController : Controller
    {
        [Produces("application/json")]
        [HttpGet("findall")]
        public async Task<IActionResult> FindAll()
        {
            try
            {
                var products = new List<Product>() {
                    new Product() { Id = "p01", Name = "name 1", Price = 2 },
                    new Product() { Id = "p02", Name = "name 2", Price = 5 },
                    new Product() { Id = "p03", Name = "name 3", Price = 6 }
                };
                return Ok(products);
            }
            catch
            {
                return BadRequest();
            }
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreWebAPIWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

Screenshots