gpt4 book ai didi

c# - 使用来自 SQL 的数据在 C# 中创建 Json 数组

转载 作者:行者123 更新时间:2023-11-30 20:35:51 24 4
gpt4 key购买 nike

我必须从 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
}

希望这能给你基本的想法。

关于c# - 使用来自 SQL 的数据在 C# 中创建 Json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37462557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com