简体   繁体   中英

How to return SQL Table as JSON in C# .Net WEB API

Below is the code from where I want to return JSON of EmployeeDetails table.

[HttpGet]
            [Route("AllEmployeeDetailsInJSON")]
            public IQueryable<EmployeeDetail> GetEmployeeInJSON()
            {
                try
                {
                    return objEntity.EmployeeDetails;
                }
                catch (Exception)
                {
                    throw;
                }
            }
public ActionResult Index()
{
     dbcontext db = new dbcontext();
     return View(db.EmployeeDetails.ToList());
}

To get JSON

public System.Web.Mvc.JsonResult GetEmployeeInJSON()
{
     dbcontext db = new dbcontext();
     var data = db.EmployeeDetails.ToList();
     return Json(data, JsonRequestBehavior.AllowGet);
}

If you are trying to use it in webapi. use following code.

While calling api, set Content-Type = "application/json"

[HttpGet]
[Route("AllEmployeeDetailsInJSON")]
public async Task<HttpResponseMessage> GetEmployeeInJSON()
{   
    try
    {
        dbcontext db = new dbcontext();
        var data = db.EmployeeDetails.ToList();
        return Request.CreateResponse(HttpStatusCode.OK, new
        {
            Data = data
        });
    }
    catch (Exception)
    {
        throw;
    }
}

So basically you have two options when you work with Web API:

First One: Use JSON.NET and return a string

You could use the Newtonsoft Nuget package. You can convert every object to JSON string with one line of code:

public string GetEmployees(){
        //Get Employees from Db:
        var employessFromDb = _context.Employees.ToList(); //Where Employees is your table name


        //Generate JSON string that we want to return
        string JSON = JsonConvert.SerializeObject(employessFromDb);

        //return the JSON
        return JSON;
}

The problem with returning a string is that your JSON will be in quotation marks and you will not send any HTTP code.

So I would use the second approach:

Second: Use the build in solution

public IHttpActionResult GetCustomers() 
    {
        var employeesFromDb = _context.Employees.ToList(); //Where Employees is your table name
        return Ok(employeesFromDb);
    }

The second approach will convert the Employees list after you return it so you don't have to care about that

No matter what way you choose, you will need a (global) variable:

private ApplicationDbContext _context;

So if you combine the given code and my answer ist would be something like this:

    [HttpGet]
    [Route("AllEmployeeDetailsInJSON")]
    public IHttpActionResult GetEmployeeInJSON()
    {
        try
        {
            var employeesFromDb = _context.Employees.ToList(); //Where Employees is your table name
            return Ok(employeesFromDb);
        }
        catch (Exception)
        {
            throw;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM