In. NET, how can I use deserialization of JSON strings/serialize generic objects toJsonStr and jsontojsonstr?
When developing a website program using the. NET Web MVC Framework, we all encounter the most critical problem: data transmission.
The ControllerBase class in. net mvc 4 is recommended to be in the form of a dynamic ViewBag data dictionary.(Type: dynamic. JavaScript is a dynamic language. type determination is performed only at runtime, not during compilation)Or use the ViewData Data dictionary (type: dictionary <string, object>) to return the bound value. That is to say, the Data Type stored in ViewBag is determined only when it is used, but the data of ViewData is determined when the object is created. The specific differences are not described in detail.
However, binding in this way has certain limitations, because the diversity of web pages makes the above method complex. For example, if five data entries are displayed in a list and 10 more data entries are displayed, we cannot use the mvc class to solve the problem. The better solution is to use AJAX + JS,
AJAX can process many types of data. Currently, JSON is widely used in data transmission because it is lightweight and intuitive. background programs provide JSON data, the front-end can use JS to complete many operations we want to do.
1) serialization, as its name implies, makes it orderly. in the program, it can be understood that a specified object is converted into a JSON key-value pair.
Background code can be easily implemented by using the. NET class library.
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Script.Serialization;using System.Runtime.Serialization;using System.Runtime.Serialization.Json;namespace Controllers{
[Serializable]
[DataContract]
Public class NewsOperationsController: Controller
{
Public ActionResult Index (){
List <T> rult = new List <T> (); // create a LIST of generic objects. // use the json method of MVC to serialize objects directly.
Return Json (rult, JsonRequestBehavior. AllowGet );}
}
}
What the foreground needs is to send a request and then process the JSON string
1 2 function getData () {3 4 $. post (appURL + "NewsOperations/index/", {}, function (data) {5 6 // convert a json object to a JSON string 7 var myJson = JSON. stringify (data); 8 9 console. log (myJson); 10 11 12}, "json"); 13}
2) deserialization
The deserialization steps are the opposite, but more complex.
The backend accepts data from the foreground in two ways.
1) transfer a json key-value pair through ajax data/submit it through form/or directly write it behind the URL. However, in this case, you still need to process the data one by one in the background. That is to say, objects to be created in the background are assigned one by one.
2) the front-end will increase the amount of code, piece together JSON objects, and send them to the backend for deserialization to initialize the objects.
The first method is more common, and the second method is something I want to try and share with you.
Front-end:
1// Submit the information. The data is submitted by concatenating JSON character arrays to provide data 2 3 function submitPage () {4 5 var da = new Date () for backend deserialization (); 6 // obtain the current time 7 var Now = da. getFullYear () + "-" + da. getMonth () + "-" + da. getDate () + "" + da. getHours () + ":" + da. getMinutes () + ":" + da. getSeconds (); 8 // Example 9 var data = [1, 2, 3, 4, 5, 6]; 10 // concatenated string ps: must be written as [{"": b, "c": d...}] format: [] represents an array object. Each {} represents a JSON object 11 var json = ""; 12 json + = "[{"; 13 json + = "\" NewsID \ ":" + data [0] + ","; 14 json + = "\" NewsTitle \": \ "" + data [0] + "\", "; 15 json + =" \ "NewsContent \": \ "" + data [0] + "\", "; 16 json + =" \ "ReporterName \": \ "" + data [0] + "\", "; 17 json + =" \ "ReporterName \": \ "" + data [0] + "\", "; 18 json + =" \ "CategoryName \": \ "" + data [0] + "\", "; 19 json + =" \ "Createtime \": \ "" + Now + "\" "; 20 json + ="}] "; 21 22 if (confirm ("whether to submit! ") = True) {23 24 $. post (appURL + "NewsOperations/submit", {index: json}, function (data) {25 26 if (data. success) {27 alert ("submitted successfully"); 28 29} else {30 31 alert ("failed to submit"); 32} 33}, "json "); 34 35} else {36} 37}
A static class is required for background processing.
1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. web; 5 using System. web. mvc; 6 using System. web. script. serialization; 7 using System. IO; 8 using System. text; 9 using System. runtime. serialization; 10 using System. runtime. serialization. json; 11 12 namespace controllers {13 public static class deserialize14 {15 // return a LIST object of the specified type 16 public static List <T> JSONStringTo List <T> (this string JsonStr) 17 {18 JavaScriptSerializer Serializer = new JavaScriptSerializer (); 19 20 List <T> objs = Serializer. deserialize <List <T> (JsonStr); 21 22 return objs; 23} 24 // return a type object 25 public static T Deserialize <T> (string json) 26 {27 T obj = Activator. createInstance <T> (); 28 29 using (MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (json) 30 {31 DataContractJsonSerializer ser Ializer = new DataContractJsonSerializer (obj. getType (); 32 33 return (T) serializer. readObject (MS); 34} 35} 36 37} 38 39 40 public ActionResult submit (string json) 41 {42 43 // deserialization JSON characters, initialize object 44 List <T> model = deserialize. JSONStringToList <T> (json); 45 //.... you can operate it on your own later !! 46 47} 48 49}
Here, the deserialization and serialization of json are all done! I haven't entered the course yet. Learn more about ING!
Interests: guitar, sing, and so on
My QQ: 601761267