且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL服务器表数据转换为JSON(C#代码)

更新时间:2023-02-07 20:46:18

创建一个镜像表的类。需要DataConract和DataMember来完成这项工作。解决方案是用VB.NET编写的



< datacontract> _ 
TableName
< datamember> _
朋友 ColumnOne 作为 字符串

< datamember> _
朋友 ColumnTwo 作为 整数
结束





将数据加载到类中。然后调用json序列化器



  Dim  oNewTable  As   TableName 
使用 oMemStream As IO.MemoryStream()
Dim oJsonSerializer 为跨度> 新跨度> Json.DataContractJsonSerializer(的GetType 跨度> (表名))
oJsonSerializer.WriteObject(oMemStream,oNewTable)
昏暗跨度> szJsonString 为跨度> 字符串跨度> = System.Text.Encoding.ASCII.GetString(oMemStream.ToArray())
结束 使用





Json Reference


如果你使用c #hindcode的asp.net,你可以在aspx和codebehind上使用sqldatasource来编写这段代码:

 受保护  void  Page_Load( object  sender,EventArgs e)
{
DataView dv =(DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
DataTable dt = dv.ToTable();
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
列表<字典><字符串,>> rows = new 列表<词典>< string,>>();
Dictionary< string,> 行;
foreach (DataRow dr in dt.Rows)
{
row = new 字典<字符串,> ();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName,dr [col]);
}
rows.Add(row);
}
string data = serializer.Serialize(rows);
string script = String .Format( < script type = \text / javascript \> var jsondata = {0}< / script>,data);
if (!this.ClientScript.IsClientScriptBlockRegistered( datascript))
{
this .ClientScript.RegisterClientScriptBlock( this .GetType(), datascript,script);
}
}
}



不要忘记在aspx页面上添加寄存器脚本块。


只有在您编写和读取数据时,JSON序列化程序才有用。所有序列化程序都允许您将一些对象图存储到流中,然后从流中恢复。粗略地说,如果您存储了一次JSON,您可以根据此结构手动计算其结构并编写JSON,或使用不同的系统编写代码,而不是使用Data Contract(例如,因为这不是.NET)。



但如果给出JSON,则需要遵循其结构。镜像数据库模式时的方法也可能不起作用,因为给定的JSON不是为您的数据库设计的。然后,您可以设计一些.NET类型以遵循给定的JSON。我在过去的答案中解释过:

如何将对象类型转换为C#类对象类型 [ ^ ],

将json数据传递给javascript? [ ^ ]。



我必须说,你没有提供足够的信息并且没有回答我的问题,所以答案是基于过多的猜测。



-SA

Hello!

I want to convert my SQL server table data into JSON format, please suggest how to do that?
:)

Create a class that mirrors your table. The DataConract and DataMember are needed to make this work. The solution is written in VB.NET

<datacontract> _
Class TableName
	<datamember> _
	Friend ColumnOne As String

	<datamember> _
	Friend ColumnTwo As Integer
End Class



Load data into the class. Then call the json serializer

Dim oNewTable As New TableName
Using oMemStream As New IO.MemoryStream()
    Dim oJsonSerializer As New Json.DataContractJsonSerializer(GetType(TableName))
    oJsonSerializer.WriteObject(oMemStream, oNewTable)
    Dim szJsonString As String = System.Text.Encoding.ASCII.GetString(oMemStream.ToArray())
End Using



Json Reference


if you asp.net with c# behindcode you can use sqldatasource on aspx and on codebehind write this code:
protected void Page_Load(object sender, EventArgs e)
        {
            DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
            DataTable dt = dv.ToTable();
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<dictionary><string,>> rows = new List<dictionary><string,>>();
            Dictionary<string,> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string,>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
                string data = serializer.Serialize(rows);
                string script= String.Format("<script type=\"text/javascript\">var jsondata = {0}</script>",data);
                if (!this.ClientScript.IsClientScriptBlockRegistered("datascript"))
                {
                    this.ClientScript.RegisterClientScriptBlock(this.GetType(), "datascript", script);
                }
            }
        }


Don't forget to add register script block on aspx page.


JSON serializer is only good if you both write and read the data. All serializers allow you to store some object graph to a stream and later restore if from stream. Roughly speaking, if you stored JSON once, you can figure out its structure and write JSON manually, following this structure, or write code using different system, not using Data Contract (for example, because this is not .NET).

But if JSON is given, you need to follow its structure. The approach when you mirror your database schema also may not work, because that given JSON wasn't designed for your database. Then you can design some .NET type to follow the given JSON. I explained it in my past answers:
How To Convert object type to C# class object type[^],
pass json data to javascript?[^].

I must say, you did not provide enough information and didn't answer my question, so the answers are based on too much of guesswork.

—SA