Web API: How To Return List Of Custom Type (JSON)

In this blog we will learn in Web API how to return list of custom type (JSON).
 
Start visual studio and select new project from the start page. Or from the File menu, select New and then Project.
 
In the Templates pane, select Installed Templates and expand visual C# node and select web. In the list of project Templates, select ASP.NET Web Application and Click OK. And give your Project name Like StudentApp.
 
 
In the new ASP.NET Project dialog, select Web API and Click Ok
 
 
We got StudentApp (our Application Name) application with all needed files
 
 
Add Model
 
Click Model Folder, add Student and ResponseModel Class with in Model Folder
 
Student Class:
  1. public class Student  
  2. {  
  3. public int ID { getset; }  
  4. public string Name { getset; }  
  5. public string Address { getset; }  
  6. public string Email { getset; }  
  7. }  
ResponseModel Class:
  1. public class ResponseModel  
  2. {  
  3. public string Message { setget; }  
  4. public bool Status { setget; }  
  5. public object Date { setget; }  
  6. }  
Actually Student Class we use for Student Property and ResponseModel Class for Return Type. We will pass all student within ResponseModel Class after few minute we will see to use this Class.
 
Add Controller
 
Click Controller Folder-->right button click-->add-->Controller and Select Web API 2 Controller, click Add and give you’re Controller Name (StudentController).
  1. namespace StudentApp.Controllers  
  2. {  
  3. public class StudentController : ApiController  
  4. {  
  5. public ResponseModel Get()  
  6. {  
  7. ResponseModel _objResponseModel = new ResponseModel();  
  8. List<Student> students = new List<Student>();  
  9. students.Add(new Student {  
  10. ID = 101,  
  11. Name="Seam",  
  12. Email="[email protected]",  
  13. Address="Dhaka,Bangladesh"  
  14. });  
  15. students.Add(new Student  
  16. {  
  17. ID = 102,  
  18. Name = "Mitila",  
  19. Email = "[email protected]",  
  20. Address = "Dhaka,Bangladesh"  
  21. });  
  22. students.Add(new Student  
  23. {  
  24. ID = 104,  
  25. Name = "Popy",  
  26. Email = "[email protected]",  
  27. Address = "Dhaka,Bangladesh"  
  28. });  
  29. _objResponseModel.Date = students;  
  30. _objResponseModel.Status = true;  
  31. _objResponseModel.Message = "Data Received successfully";  
  32. return _objResponseModel;  
  33. }  
  34. }  
  35. }  
And run, give url (/api/student) we can see output