Asp. NET uses data from SQL Server to generate a JSON string

Source: Internet
Author: User
Tags sql 2008 serialization tojson

Source: Author: Water-Scarce dolphin sources: Blog Park Published: 2010-09-21 21:47 read: 6,136 recommendations: 0 original link [favorites]absrtact: The data content used by ExtJS is basically JSON format, and to be developed with ASP, it is necessary to format the data into JSON. So the author implements a method for generating a JSON string.

Recently in Learning ExtJS and ASP, the former use of data content is basically JSON format, and then want to write a format data into JSON, find a bit on the internet, found quite a lot of, realized a similar to ToString () method, name Yue: ToJson ( )。

But what I see on the internet is basically a copy of Scott's masterpiece, more than 90% of them (I'm not saying that Scott Prawn's masterpiece has any bad, no meaning), so I also drew a gourd. Nonsense is not much to say, go straight to the chase.

Let's talk about my development environment:

Windows Server DataCenter

Visual Studio Team System

SQL Server 2005 Developer (SQL 2008 has been officially released, ready for upgrade, ^_^)

I wrote a Tojson () out of Scott's masterpiece (a link in the original and Chinese version at the end of this article). The code is as follows:

?
123456789101112131415161718192021222324252627282930313233 using System;using System.Web.Script.Serialization;namespace Demo{    /// <summary>    /// JSON帮助类    /// </summary>    public static class JsonHelper    {        /// <summary>        /// 格式化成Json字符串        /// </summary>        /// <param name="obj">需要格式化的对象</param>        /// <returns>Json字符串</returns>        public static string ToJson(this object obj)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            return serializer.Serialize(obj);        }        /// <summary>        /// 格式化成Json字符串        /// </summary>        /// <param name="obj">需要格式化的对象</param>        /// <param name="recursionDepth">指定序列化的深度</param>        /// <returns>Json字符串</returns>        public static string ToJson(this object obj, int recursionDepth)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            serializer.RecursionLimit = recursionDepth;            return serializer.Serialize(obj);        }    }}

A word does not miss the shot, it should be no problem (later found Scott masterpiece at the end of the note, forget to read, it is careless AH ~~~*_*)!

But in the editing, although the success, but found that there are 2 warnings, because I write the program has been to do their best to ensure that the number of warnings written by the program is the least, so, of course, to see what these two warnings are.

The warning is: "System.Web.Script.Serialization.JavaScriptSerializer.JavaScriptSerializer ()" is obsolete: "The recommended Alternative is System.Runtime.Serialization.DataContractJsonSerializer. "

Remember the beginning of the time to learn ASP, in the use of appsettings time (specific which method is not clear) also appeared a similar warning, and finally used ConfigurationManager instead of the warning has not appeared, then this time should be similar.

So go to MSDN and see what's going on. Don't understand, then to CSDN look at it. Still don't understand, finally, help Google. NND, tossing for a long time, still do not know what is going on.

Replace it with "DataContractJsonSerializer", but there is less reference to "System.Runtime.Serialization", add the reference to it, or not compile it.

Never know what is going on, finally, lucky Google to a demo, but also use "DataContractJsonSerializer" to replace the appeal of outdated warnings. The link in the note at the end of Scott's masterpiece.

Finally, I understand what's going on. The steps to resolve are as follows:

First, add a reference to the two DLLs, respectively: System.Runtime.Serialization.dll, System.ServiceModel.Web.dll.

After adding the references, add the using statement in the CS code page as follows:

?
123 using System;using System.IO;using System.Runtime.Serialization.Json;

Note: Because you want to use the stream and other things, so here to add System.IO this namespace.

A total of three using statements, after the addition, you can begin to write code, the code is as follows:

?
1234567891011121314151617181920212223242526 namespace Demo{    /// <summary>    /// JSON帮助类    /// </summary>    public static class JsonHelper    {        /// <summary>        /// 格式化成Json字符串        /// </summary>        /// <param name="obj">需要格式化的对象</param>        /// <returns>Json字符串</returns>        public static string ToJson(this object obj)        {            // 首先,当然是JSON序列化            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());            // 定义一个stream用来存发序列化之后的内容            Stream stream = new MemoryStream();            serializer.WriteObject(stream, obj);            // 从头到尾将stream读取成一个字符串形式的数据,并且返回            stream.Position = 0;            StreamReader streamReader = new StreamReader(stream);            return streamReader.ReadToEnd();        }    }}

In this way, the writing of this class is complete, and the rest is called.

First create a new library class project (name any) in Visual Studio 2008, add the above content to the project, and compile it into a DLL file for WebApplication (or website) calls. The project I built here is called demo, and the compiled DLL is called Demo.dll.

Then create a new database in SQL Server 2005, configure the link string in Web. config, and you can read the data anyway, which is no longer detailed. The database I built here is called Test, and the table name is Test_table_01, and the fields are: TestID (int), Title (varchar), Body (varchar), Remark (varchar (200)), Some content has been added to the field.

Create a new WebApplication (or website) in Visual Studio 2008 and add a reference to the Demo.dll above, and you need to add a reference to "System.Runtime.Serialization". Because the entity layer is added later, the attributes of the entity layer need to be serialized. What I'm building here is WebApplication, named Test.

The App_Code folder was added to test and a class was added, called TestClass.cs.

This class is used to map the table test_table_01 in the database test, and after adding a good CS file, write the following code (the new feature of C # 3.5 ^_^):

?
1234567891011121314151617 using System;using System.Runtime.Serialization;namespace Test{    [DataContract]    public class TestClass    {        [DataMember]        public int TestID { get; set; }        [DataMember]        public string Title { get; set; }        [DataMember]        public string Body { get; set; }        [DataMember]        public string Remark { get; set; }    }}

Note: If you want to serialize the class, be sure to add "[DataContract]" Before the class and add "[DataMember]" before the property so that it can be serialized as JSON by "DataContractJsonSerializer".

After adding the TestClass.cs file, create a new Default.aspx page in the root directory, place a label in the page, and go to the background code.

Add "using Demo;", "Using System.Collections.Generic;" on the CS code; and "Using System.Data.SqlClient;" These three using statements.

Then create a new method to get the data in the database, and to fill the obtained content into the generic (the code given here, DataAccess is my own according to SqlHelper rewrite a database access class, in fact, directly with the SqlHelper can be), the code is as follows:

?
1234567891011121314151617181920212223242526272829303132333435 // 获取表中的所有数据private List<TestClass> GetAllData(){    List<TestClass> list = new List<TestClass>();    string strSql = "SELECT * FROM Test_Table_01";    SqlCommand cmd = new SqlCommand(strSql);    DataAccess da = new DataAccess();    try    {        SqlDataReader sdr = da.ExecuteReader(cmd);        while (sdr.Read())        {            list.Add(this.FillDetailWithReader(sdr));        }    }    finally    {        da.DisConnect();    }    return list;}// 向泛型填充数据private TestClass FillDetailWithReader(SqlDataReader reader){    TestClass model = new TestClass();    if (reader["TestID"] != DBNull.Value)        model.TestID = (int)reader["TestID"];    if (reader["Title"] != DBNull.Value)        model.Title = (string)reader["Title"];    if (reader["Body"] != DBNull.Value)        model.Body = (string)reader["Body"];    if (reader["Remark"] != DBNull.Value)        model.Remark = (string)reader["Remark"];    return model;}

Once these two methods have been written, they can be called. Enter the following code in the Page_Load event:

?
12345678910 protected void Page_Load(object sender, EventArgs e){    if (!IsPostBack)    {        // 首先调用GetAllData()方法获取数据库中的数据        List<TestClass> list = this.GetAllData();        // 将泛型list格式化成JSON字符串,并且赋值到Label1中去        Label1.Text = list.ToJson();    }}

This completes the process of reading data from SQL Server, formatting it as a JSON string, and entering it.

Today there are many things on the web, such as what to read with LINQ, or not SQL Server, XML, and so on, by everyone to explore.

Asp. NET uses data from SQL Server to generate a JSON string

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.