Generate JSON format

Source: Internet
Author: User

HTML page

<type= "button"  value= "Regenerate json"  class= "Button1 "  ID="createjson"/>

JavaScript section

<script type= "Text/javascript" > $ (function  () {             // generate JSON            $ ("#Createjson"). Click (function  () {                $.post ("newscategory.aspx?  Actionfunction  (JSON) {                    alert (json.msg);      });}); </script>

Background code

    protected voidPage_Load (Objectsender, EventArgs e) {        if(request.headers["X-requested-with"] !=NULL&& request.headers["X-requested-with"]. ToLower () = ="XMLHttpRequest".            ToLower ()) {response.clear (); Response.ContentType="Application/json"; if(request["Action"] =="Create") {Response.Write (Createjson ());        } response.end (); }    }
View Code

     /// <summary>    ///generate merchant Category JSON/// </summary>    /// <returns></returns>    protected string Createjson () {System.Web.Script.Serialization.JavaScriptSerializer json=NewSystem.Web.Script.Serialization.JavaScriptSerializer (); //Initialize (reference space using System.Text; )
StringBuilder SB=NewStringBuilder (); varList =Express.BLL.NewsCategory.Get (); foreach(varIteminchlist) { if(sb.) Length >0) sb. Append (","); Sb. Append (string. Format ("{{\ "id\": {0},\ "name\": \ "{1}\", \ "pid\": {2},\ "itemvalue\": \ "{3}\ "", item. Id, getunicode(item. ItemName), item. ParentID, item. Itemvalue)); Sb. Append ("}"); }     //Returns the physical file path corresponding to the specified virtual path on the Web server
stringFilePath = Server.MapPath (@"/common/newscategoryjson.js"); //Creates a new file and writes the specified string, overwriting the file if the destination file already exists
System.IO.File.WriteAllText (filePath, "[" + sb. ToString () + "]" , System.Text.Encoding.UTF8); returnJson. Serialize (New{Code =1,msg="Build Complete" }); }

Converting Chinese characters to Unicode encoding

 /// <summary>    ///get Unicode encoding of Chinese characters/// </summary>    protected stringGetunicode (stringtext) {        stringresult ="";  for(inti =0; I < text. Length; i++)        {            if((int) Text[i] > +&& (int) Text[i] <127) {result+=Text[i].            ToString (); }            Elseresult+=string. Format ("\\u{0:x4}", (int) text[i]); }        returnresult; }
View Code

Database section

        ///Get all/// </Summary>         PublicList<Model.newscategory>Get () {String SQL="Select *  fromNewscategoryOrder  by  Case  whenParentID=0  ThenId*10000 ElseParentID*10000+IdEnd"; List<Model.newscategory>List=New List<Model.newscategory>(); using (SqlDataReader Dr=DBUtility.SqlHelper.ExecuteReader (Connstring.connreadonly, CommandType.TextSqlNULL))            {                 while(Dr.Read()) {model.newscategory Model=new Model.newscategory ();                    Object obj; Obj=Dr["Id"]; if(obj!= NULL &&Obj!=DBNull.Value) {model. Id=(int) obj; } obj=Dr["Sortvalue"]; if(obj!= NULL &&Obj!=DBNull.Value) {model. Sortvalue=(int) obj; } obj=Dr["ParentID"]; if(obj!= NULL &&Obj!=DBNull.Value) {model. ParentID=(int) obj; } model. ItemName=Dr["ItemName"].                    ToString (); Model. Itemvalue=Dr["Itemvalue"].                    ToString (); List.ADD(model); }            }            returnlist; }
View Code

Run results
Common/newscategoryjson.js

[{"id": 31,"name": "\U65B0\U95FB\U4E2D\U5FC3", "pid": 0, "Itemvalue": "|0|"},
{"id": Wuyi, "name": "\u4f01\u4e1a\u5feb\u8baf", "pid": +, "Itemvalue": "|0|31|"},
{"id": *, "name": "\u4f01\u4e1a\u516c\u544a", "pid": "Itemvalue": "|0|31|"},
{"id": +, "name": "\u884c\u4e1a\u52a8\u6001", "pid": +, "Itemvalue": "|0|31|"},
{"id": "\U65B0\U95FB\U4E2D\U5FC3", "pid": "$", "Itemvalue": "|0|31|"},
{"id": "Name": "\u4f01\u4e1a\u5feb\u8baf", "pid": "Itemvalue": "|0|31|"},
{"id": 94, "name": "\u4f01\u4e1a\u516c\u544a", "pid": +, "Itemvalue": "|0|31|"},
{"id": +, "name": "\u6d4b\u8bd5", "pid": +, "Itemvalue": "|0|31|"},
{"id": 181, "name": "\u6d4b\u8bd5111", "pid": +, "Itemvalue": "|0|31|"},


{"id": Si, "name": "\u5173\u4e8e\u76df\u53cb\u634c\u634c", "pid": 0, "Itemvalue": "|0|"},
{"id": "Name": "\u4f01\u4e1a\u6982\u51b5", "pid": Si, "itemvalue": "|0|54|"},
{"id": "" "," "Name": "\u4f01\u4e1a\u6587\u5316", "pid": Si, "itemvalue": "|0|54|"},
{"id": $, "name": "\u4f01\u4e1a\u53d1\u5c55", "pid": Si, "itemvalue": "|0|54|"}
......
]

Points of knowledge involved

1, Server.MapPath (string path);

2, System.IO.File.WriteAllText (Sting path,string contents,encoding Encoding);

Generate JSON format

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.