Convert List Objects to/from JSON in ASP.NET Web API and Entity Framework


Create a database with the name is LearnASPNETWebAPIWithRealApps. This database have a table: product table.

--
-- Table structure for table `product`
--

CREATE TABLE Product (
	Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
	Name varchar(50) NULL,
	Price money NULL,
	Quantity int NULL,
	Status bit NULL,
	CreationDate date NULL
)

--
-- Dumping data for table `product`
--

INSERT Product (Name, Price, Quantity, Status, CreationDate) VALUES ('Name 1', 12.3000, 3, true, '2017-10-20')
INSERT Product (Name, Price, Quantity, Status, CreationDate) VALUES ('Name 2', 25.1000, 8, false, '2017-11-12')
INSERT Product (Name, Price, Quantity, Status, CreationDate) VALUES ('Name 3', 23.9000, 2, true, '2017-12-26')
INSERT Product (Name, Price, Quantity, Status, CreationDate) VALUES ('Name 4', 89.2000, 11, false, '2017-09-17')

Structure of Product Table

Data of Product Table




Create entity class – ProductEntity.cs, to represent the above table

ProductEntity.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LearnASPNETWebAPIWithRealApps.Models
{
    public class ProductEntity
    {
        public int Id
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public decimal Price
        {
            get;
            set;
        }

        public int Quantity
        {
            get;
            set;
        }

        public bool Status
        {
            get;
            set;
        }

        public string CreationDate
        {
            get;
            set;
        }

    }
}

Use the Entity Wizard to create an Entity Data Model From Database in Visual Studio.

Structure of Project




Create Web API Controller use Entity Framework read data from database provides application/json data to the client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using LearnASPNETWebAPIWithRealApps.Models;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Data.Entity;

namespace LearnASPNETWebAPIWithRealApps.Controllers
{

    [RoutePrefix("api/product")]
    public class ProductRestController : ApiController
    {
        private LearnASPNETWebAPIWithRealAppsEntities db = new LearnASPNETWebAPIWithRealAppsEntities();

        [HttpGet]
        [Route("find")]
        public HttpResponseMessage find()
        {
            try
            {
                var Products = db.Products.Select(p => new ProductEntity()
                {
                    Id = p.Id,
                    Name = p.Name,
                    Price = p.Price.Value,
                    Quantity = p.Quantity.Value,
                    Status = p.Status.Value,
                    CreationDate = p.CreationDate.Value.Year + "-" + p.CreationDate.Value.Month + "-" + p.CreationDate.Value.Day
                }).ToList();
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StringContent(JsonConvert.SerializeObject(Products));
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return response;
            }
            catch
            {
                return new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
        }

    }
}

Access Web API use the following url: http://localhost:64967/api/product/find

Output

[
    {"Id":1,"Name":"Name 1","Price":12.3000,"Quantity":3,"Status":true,"CreationDate":"2017-10-20"},
    {"Id":2,"Name":"Name 2","Price":25.1000,"Quantity":8,"Status":false,"CreationDate":"2017-11-12"},
    {"Id":3,"Name":"Name 3","Price":23.9000,"Quantity":2,"Status":true,"CreationDate":"2017-12-26"},
    {"Id":4,"Name":"Name 4","Price":89.2000,"Quantity":11,"Status":false,"CreationDate":"2017-9-17"}
]

Create Console Application Project in Visual Studio.

Create Models folder in Console Application. Create a entity class: ProductEntity.cs as below

Product.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LearnASPNETWebAPIWithRealApps_Client.Models
{
    public class ProductEntity
    {
        public int Id
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public decimal Price
        {
            get;
            set;
        }

        public int Quantity
        {
            get;
            set;
        }

        public bool Status
        {
            get;
            set;
        }

        public string CreationDate
        {
            get;
            set;
        }

    }
}




DemoRestClientModel class contain methods call Web API. Add reference to System.Net.Http.Formatting

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;

namespace LearnASPNETWebAPIWithRealApps_Client
{
    public class DemoRestClientModel
    {
        private string BASE_URL = "http://localhost:64967/api/product/";

        public Task<HttpResponseMessage> find()
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(BASE_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                return client.GetAsync("find");
            }
            catch
            {
                return null;
            }
        }

    }
}
using LearnASPNETWebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETWebAPIWithRealApps_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            DemoRestClientModel demoRestClientModel = new DemoRestClientModel();

            HttpResponseMessage httpResponseMessage = demoRestClientModel.find().Result;

            HttpStatusCode httpStatusCode = httpResponseMessage.StatusCode;
            Console.WriteLine("Status Code: " + httpStatusCode);

            bool isSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode;
            Console.WriteLine("IsSuccessStatusCode: " + isSuccessStatusCode);

            List<ProductEntity> products = httpResponseMessage.Content.ReadAsAsync<List<ProductEntity>>().Result;
             Console.WriteLine("Product List");
            foreach (var product in products)
            {
                Console.WriteLine("Id: " + product.Id);
                Console.WriteLine("Name: " + product.Name);
                Console.WriteLine("Price: " + product.Price);
                Console.WriteLine("Quantity: " + product.Quantity);
                Console.WriteLine("Status: " + product.Status);
                Console.WriteLine("Creation Date: " + product.CreationDate);
                Console.WriteLine("============================");
            }

            Console.ReadLine();
        }
    }
}




Status Code: OK
IsSuccessStatusCode: True
Product List
Id: 1
Name: Name 1
Price: 12.3000
Quantity: 3
Status: True
Creation Date: 2017-10-20
============================
Id: 2
Name: Name 2
Price: 25.1000
Quantity: 8
Status: False
Creation Date: 2017-11-12
============================
Id: 3
Name: Name 3
Price: 23.9000
Quantity: 2
Status: True
Creation Date: 2017-12-26
============================
Id: 4
Name: Name 4
Price: 89.2000
Quantity: 11
Status: False
Creation Date: 2017-9-17
============================