Let's first encapsulate a class! This kind of online can be found! There's this class, everything will be easy, haha.
Copy Code code 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>
Serializing an object to a JSON string
</summary>
<typeparam name= "T" > Object type </typeparam>
<param name= "obj" > Object Entities </param>
<returns>json string </returns>
public static string getjson<t> (T obj)
{
Remember to add a reference System.ServiceModel.Web
/**
* If the above reference is not added, System.Runtime.Serialization.Json; JSON's not coming out.
* */
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>
To restore a JSON string to an object
</summary>
<typeparam name= "T" > Object type </typeparam>
<param name= "Szjson" >json string </param>
<returns> Object Entities </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);
}
}
}
To test an entity class:
Copy Code code 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 Code 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)
{
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) {//Using the Eval function
var json = eval (JSONSTR); Because the list is set above
for (var i = 0; i < json.length; i++) {
Alert (json[i). Id + "Name:" + json[i]. Name);
}
}
</script>
<title></title>
<body>
<form id= "Form1" runat= "Server" >
<div>
</div>
</form>
</body>
About JSON string conversions to entities please test it yourself! As long as there is the Jsonhelper class, everything is good to do!