Generate json format and generate json
Html page
<Input type = "button" value = "regenerate JSON" class = "button1" id = "createjson"/>
Javascript Section
<Script type = "text/javascript"> $ (function () {// generate JSON $ ("# createjson "). click (function () {$. post ("NewsCategory. aspx? Action = create ", function (json) {alert (json. msg) ;}); </script>
Background code
Protected void Page_Load (object sender, 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 the merchant category Json /// </summary> /// <returns> </returns> protected string CreateJson () {System. web. script. serialization. javaScriptSerializer json = new System. web. script. serialization. javaScriptSerializer (); // initialization (reference space using System. text ;)
StringBuilder sb = new StringBuilder (); var list = Express. BLL. newsCategory. get (); foreach (var item in list) {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.
String filePath = Server. MapPath (@ "/common/newscategoryJson. js"); // create a new file and write the specified string. If the target file already exists, overwrite the file.
System. IO. file. writeAllText (filePath, "[" + sb. toString () + "]", System. text. encoding. UTF8); return json. serialize (new {code = 1, msg = "generated "});}
Convert Chinese characters to Unicode encoding
/// <Summary> /// obtain the Unicode encoding of Chinese characters /// </summary> protected string GetUnicode (string text) {string result = ""; for (int I = 0; I <text. length; I ++) {if (int) text [I]> 32 & (int) text [I] <127) {result + = text [I]. toString ();} else result + = string. format ("\ u {0: x4}", (int) text [I]);} return result ;}View Code
Database Section
/// Get all /// </summary> public List <Model. newsCategory> Get () {string SQL = "select * from NewsCategory order by case when ParentId = 0 then Id * 10000 else ParentId * 10000 + Id end"; List <Model. newsCategory> list = new List <Model. newsCategory> (); using (SqlDataReader dr = DBUtility. sqlHelper. executeReader (ConnString. connReadonly, CommandType. text, SQL, null) {while (dr. read () {Model. newsCategory mod El = 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) ;}} return list ;}View Code
Running result
Common/newscategoryJson. js
[{"id":31,"name":"\u65b0\u95fb\u4e2d\u5fc3","pid":0,"itemvalue":"|0|"},
{"id":51,"name":"\u4f01\u4e1a\u5feb\u8baf","pid":31,"itemvalue":"|0|31|"},
{"id":52,"name":"\u4f01\u4e1a\u516c\u544a","pid":31,"itemvalue":"|0|31|"},
{"id":53,"name":"\u884c\u4e1a\u52a8\u6001","pid":31,"itemvalue":"|0|31|"},
{"id":91,"name":"\u65b0\u95fb\u4e2d\u5fc3","pid":31,"itemvalue":"|0|31|"},
{"id":93,"name":"\u4f01\u4e1a\u5feb\u8baf","pid":31,"itemvalue":"|0|31|"},
{"id":94,"name":"\u4f01\u4e1a\u516c\u544a","pid":31,"itemvalue":"|0|31|"},
{"id":180,"name":"\u6d4b\u8bd5","pid":31,"itemvalue":"|0|31|"},
{"id":181,"name":"\u6d4b\u8bd5111","pid":31,"itemvalue":"|0|31|"},
{"id":54,"name":"\u5173\u4e8e\u76df\u53cb\u634c\u634c","pid":0,"itemvalue":"|0|"},
{"id":55,"name":"\u4f01\u4e1a\u6982\u51b5","pid":54,"itemvalue":"|0|54|"},
{"id":56,"name":"\u4f01\u4e1a\u6587\u5316","pid":54,"itemvalue":"|0|54|"},
{"id":57,"name":"\u4f01\u4e1a\u53d1\u5c55","pid":54,"itemvalue":"|0|54|"}
......
]
Knowledge points involved
1. Server. MapPath (string path );
2. System. IO. File. WriteAllText (sting path, string contents, Encoding encoding );
C # generate json format
It is divided into two parts:
Type 1 definition, which can be manually defined or defined using tools. I personally use a vs2012 plug-in and can choose to paste json as a class, this plug-in is currently a beta version, so it is not recommended. You can choose other similar tools
Public class Rootobject
{
Public Programmer [] programmers {get; set ;}
Public Author [] authors {get; set ;}
Public Musician [] musicians {get; set ;}
}
Public class Programmer
{
Public string firstName {get; set ;}
Public string lastName {get; set ;}
Public string email {get; set ;}
}
Public class Author
{
Public string firstName {get; set ;}
Public string lastName {get; set ;}
Public string genre {get; set ;}
}
Public class Musician
{
Public string firstName {get; set ;}
Public string lastName {get; set ;}
Public string instrument {get; set ;}
}
The second part is data filling and conversion. I will demonstrate the process here, so I will fill in the data as needed, and you will change it yourself.
Rootobject B = new Rootobject ()
{
Programmers = new Programmer [] {
New Programmer () {firstName = "Brett", lastName = "McLaughlin", email = "aaaa "},
New Programmer () {firstName = "Jason", lastName = "Hunter", email = "bbbb "}
},
Authors = new Author [] {
New Author () {firstName = "fa", lastName = "la", genre = "ga "},
New Author () {firstName = "fa1", lastName = "la1", genre = "ga1 "}
},
Musicians = n ...... the remaining full text>
How does js generate json data?
Var row1 = {};
Row1.name = 'David ';
Row1.age = '20 ';
// Or
Var row2 = {name: 'Peter ', age: '23 '};
Var data = [];
Data. push (row1 );
Data. push (row2 );
// The json string of data is [{name: 'David ', age: '20'}, {name: 'Peter', age '23'}]
// If the background is PHP, you will get
/*
Print_r ($ _ GET );
Array (0 => array ('name' => 'David '....
*/
However, the following format is recommended:
Var data = {records: []};
Data. records. push (row1 );
Data. records. push (row2 );
// The json string of data is {records: [{name: 'David ', age: '20'}, {name: 'Peter', age '23'}]}.
// If the background is PHP, you will get
/*
Print_r ($ _ GET );
Array (
'Records' => array (
0 => array (
'Name' => 'David'
....
*/