我必须从SQL获取数据并将其作为JSON发送到应用程序的前端。我的C#不好,所以我很困惑。目前,我收到的不是有效的JSON:
{"name":"Perez","company":"test"}{"name":"Jespersen","company":"Codeparc"}
如您所见,它不是作为数组来的。我该如何实现?我的代码:
using System;
using System.Data.SqlClient;
using Newtonsoft.Json;
namespace eltklt_webapp
{
//Create the Client Object
public class Client
{
public string name;
public string company;
}
public partial class getData : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["type"] == "clients")
{
// SQL Server Read Statement Sample
using (SqlConnection conn = new SqlConnection(Gizmos.getConnectionString()))
{
SqlCommand command = new SqlCommand("select * from clients", conn);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Client Client = new Client();
Client.name = reader["name"].ToString();
Client.company = reader["company"].ToString();
string jsonString = JsonConvert.SerializeObject(Client);
Response.Write(jsonString);
}
}
}
Response.End();
}//end if Clients
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["type"] == "clients")
{
List<Client> clients=new List<Client>();
// SQL Server Read Statement Sample
using (SqlConnection conn = new SqlConnection(Gizmos.getConnectionString()))
{
SqlCommand command = new SqlCommand("select * from clients", conn);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Client Client = new Client();
Client.name = reader["name"].ToString();
Client.company = reader["company"].ToString();
clients.Add(Client);
//string jsonString = JsonConvert.SerializeObject(Client);
}
}
}
var jsonString = JsonConvert.SerializeObject(clients);
Response.Write(jsonString);
Response.End();
}//end if Clients
}
希望这可以给您基本的想法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句