Example code for ASP.net JSON strings to and from entity classes

Source: Internet
Author: User
Tags eval json object serialization serialization

  This article is mainly on the ASP.net JSON string and entity classes of the conversion of the sample code is introduced, the need for friends can come to the reference, I hope to help you.

Let's first encapsulate a class! This kind of online can be found! There's this class, everything will be easy, haha. The code is as follows: using System; Using System.Collections.Generic; Using System.Linq; Using System.Web; Using System.Runtime.Serialization.Json; Using system.servicemodel.web;///Remember to reference this namespace using System.IO; Using System.Text; <summary>///Summary description for Jsonhelper///</summary> public class Jsonhelper {    PU Blic Jsonhelper ()     {       //       //Todo:add Constructor Logi C here        //    {   ///<summary>    ///object serialization JSON string & nbsp    ///</summary>    ///<typeparam name= "T" > Object type </typeparam>    ///&L T;param name= "obj" > object entity </param>    ///<returns>json string </returns>     Public static string getjson<t> (T obj)     {       //Remember to add Reference system.servicemodel.web    &NBsp    /**          * If the above reference is not added, System.Runtime.Serialization.Json; JSON is not out of the OH          * *         DataContractJsonSerializer json = new DataCo Ntractjsonserializer (typeof (T));         using (MemoryStream ms = new MemoryStream ())         {    &NBSP ;       JSON. WriteObject (MS, obj);             String Szjson = Encoding.UTF8.GetString (ms. ToArray ());             return Szjson;        }     {   ///<summary>    ///restore JSON string to object   &NB Sp </summary>    ///<typeparam name= "T" > Object type </typeparam>    ///<param name= "Szjson" >json string </param>    ///<returns> object entity </returns>     public static T Parseformjson<t> (String szjson)   &nbsP {        T obj = activator.createinstance<t> ();         using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (Szjson))         {            DataContractJsonSerializer DCJ = new DataContractJsonSerializer (typeof (T));             return (T) DCJ. ReadObject (MS);        }    }}   Test entity class: Code: public class TestData {    public TestData (     {   }     public int Id {get; set;}     public string Name {get; set;}     public string Sex {get; set;}}   Test page:   Code as follows: <%@ page language= "C #"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">   <script runat=" Server ">     protected void Page_Load (object sender, EventArgs e)   &NBSP ; {        String jsonstr = string. Empty;         list<testdata> TDS = new list<testdata> ();        //test data         for (int i = 1; i < 4; i++)         {            TDs. ADD (New TestData () {Id = i, Name = "Jinho" + I, Sex = "Male"});        }        //convert a list to JSON string         JSONSTR = Jsonhel Per. Getjson<list<testdata>> (TDS);         Response.Write (JSONSTR);         this. Page.ClientScript.RegisterStartupScript (this. GetType (), "JSON", "Getjson (" + Jsonstr + ");", true);    }   </script> <script type= "Text/javascript" >     function Getjson (jsonstr) {&NB Sp      //Use the eval function         var json = eval (JSONSTR);        //Because of the list set    nbsp   for (var i = 0; i < json.length i++) {            alert (json[i). Id + "Name:" + json[i]. Name);        }    } </script> <html xmlns= "http://www.w3.org/1999/xhtml" > <head R unat= "Server" >     <title></title> </head> <body>     <form id= "Form1 "runat=" server >     <div>       </div>     </form> </body> </html>     About JSON string conversion to entities please test it yourself! As long as there is the Jsonhelper class, everything is good to do!
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.