如何将SQL Server查询结果的数据转换为JSON格式?

oJM*_*86o 9 javascript sql-server ajax json

我刚刚了解Ajax和JSON格式.我正在构建一个非常简单的地址簿.因此,假设我有一个表,为简单起见有3列:

Name, Email and Phone

我的javascript/jquery不是最好的学习,但我想把我的SQL Server返回的数据放到JSON格式.我应该创建一个存储过程,可以创建一个json文件并将其放在我可以在我的JavaScript中使用它的文件夹中吗?

或者这就像客户端C#/ VB.net应用程序应该在每个说5分钟实际生成文件的地方做什么?基本上我们假设我得到一些数据:

George g@yahoo.com 123-3333
Mike m@gmail.com 123-4433
Steve s@gmail.com 144-3333
Jill r@gmail.com 333-3333
Run Code Online (Sandbox Code Playgroud)

我从一个简单的select语句中得到了回复:

SELECT name, email, phone from myTable

然后我怎么能把它作为一个json文件,这样我就可以将数据存储在a中.json,然后在我的javascript代码中使用该文件.有人可以解释这个以及人们如何生成json文件吗?

Joe*_*ide 10

通常,更好的方法是通过一些web api提供JSON.

这是一个如何在ASP.NET MVC中执行此操作的示例:

http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

public class Contact
{
  public string Name {get;set;}
  public string Email {get;set;}
  public string Phone {get;set;}
}

public class ContactsController : ApiController
    {
        // instead of having the contacts in memory, you can load them from the database using Entity Framework, Dapper.NET - or you other favorite ORM.
        Contact[] contacts = new Contact[] 
        { 
            new Contact{ Name = "George", Email = "g@yahoo.com", Phone = "123-3333" }, 
            new Contact{ Name = "Mike", Email = "m@yahoo.com", Phone = "123-3333" }, 
            new Contact{ Name = "Steve", Email = "s@yahoo.com", Phone = "123-3333" } 
        };

        public IEnumerable<Contact> GetAllContacts()
        {
            return contacts;
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后,您将浏览到:http://localhost:xxxx/api/contacts/并且您可以看到您的数据.您可以使用javascript以JSON格式检索数据.Web API负责为您将其转换为JSON.

在幕后,ASP.NET MVC使用NewtonSoft的JSON.NET将类转换为JSON.这是开源的,可以在任何.NET应用程序中使用.

http://james.newtonking.com/pages/json-net.aspx

使用jQuery检索数据:

<script type="text/javascript">
    $(document).ready(function () {
        // Send an AJAX request
        $.getJSON("api/contacts/",
        function (data) {
            // On success, 'data' contains a list of contacts.
            $.each(data, function (key, val) {

                console.log(val.Name, val.Phone, val.Email);  
            });
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

如果您的项目使用的是ASP.NET Web窗体,则可以执行以下操作:

asp.net web表单json返回结果

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public List<Contact> GetAllContacts()
{
  return contacts;
}
Run Code Online (Sandbox Code Playgroud)

  • 更新了使用[WebMethod] for WebForms显示的答案. (2认同)