Sample Code for mutual conversion between ASP. net json strings and object classes

Source: Internet
Author: User

Encapsulate a class first! This category can be found on the Internet! With this class, everything will become simple, haha.
Copy codeThe 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
{
Public JsonHelper ()
{
//
// TODO: Add constructor logic here
//
}
/// <Summary>
/// Serialize the object to a JSON string
/// </Summary>
/// <Typeparam name = "T"> Object Type </typeparam>
/// <Param name = "obj"> Object object </param>
/// <Returns> JSON string </returns>
Public static string GetJson <T> (T obj)
{
// Remember to add reference System. ServiceModel. Web
/**
* If the above reference is not added, System. Runtime. Serialization. Json; Json is supplied.
**/
DataContractJsonSerializer json = new DataContractJsonSerializer (typeof (T ));
Using (MemoryStream MS = new MemoryStream ())
{
Json. WriteObject (MS, obj );
String szJson = Encoding. UTF8.GetString (ms. ToArray ());
Return szJson;
}
}
/// <Summary>
/// Restore the JSON string to an object
/// </Summary>
/// <Typeparam name = "T"> Object Type </typeparam>
/// <Param name = "szJson"> JSON string </param>
/// <Returns> Object entity </returns>
Public static T ParseFormJson <T> (string szJson)
{
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 object class:
Copy codeThe Code is as follows:
Public class TestData
{
Public TestData ()
{
}
Public int Id {get; set ;}
Public string Name {get; set ;}
Public string Sex {get; set ;}
}

Test page:
Copy codeThe Code is 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)
{
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 a json string
JsonStr = JsonHelper. 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) {// use the eval function
Var json = eval (jsonStr); // The above is the list set
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 runat = "server">
<Title> </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>

</Div>
</Form>
</Body>
</Html>

Please test the conversion of json strings to entities! Everything can be done as long as there is the JsonHelper class above!

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.