The method of JSON serialization and deserialization in ASPNET, aspnetjson serialization
1. Introduction to JSON
JSON (JavaScript Object Notation, JavaScript Object Notation) is a lightweight data exchange format.
JSON is a set of "name-value pairs. The structure consists of braces '{}', braces '[]', comma ',', colons ':', and double quotation marks '. The data types include Object, Number, boolean, String, Array, and NULL.
JSON has the following forms:
An Object is an unordered set of "name-value pairs". An Object starts with "{" and ends. Each "name" is followed by one ":". Multiple "name-value pairs" are separated by commas. For example:
Var user = {"name": "Zhang San", "gender": "male", "birthday": "1980-8-8 "}
An Array is an ordered set of values. An Array starts with "[" and ends with "]" and is separated. For example:
Var userlist = [{"user": {"name": "Zhang San", "gender": "male", "birthday": "1980-8-8 "}}, {"user": {"name": "", "gender": "male", "birthday": "1985-5-8"}];
A String is a collection of any number of Unicode characters enclosed by double quotes. It is escaped using a backslash.
Ii. serialize and deserialize JSON data
You can use the DataContractJsonSerializer class to serialize a type instance to a JSON string and deserialize the JSON string to a type instance. DataContractJsonSerializer in the SystemRuntimeSerializationJson namespace, NET Framework 5 is included in SystemServiceModelWebdll and must be referenced. NET Framework 4 is in SystemRuntimeSerialization.
Code for serialization and deserialization using DataContractJsonSerializer:
Using System; using SystemCollectionsGeneric; using SystemLinq; using SystemWeb; using SystemRuntimeSerializationJson; using SystemIO; using SystemText; /// <summary> /// JSON serialization and deserialization helper class /// </summary> public class JsonHelper {// <summary> // JSON serialization /// </summary> public static string JsonSerializer <T> (T t) {DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T); MemoryStream MS = new MemoryStream (); serWriteObject (MS, t); string jsonString = EncodingUTFGetString (msToArray ()); msClose (); return jsonString;} // <summary> // JSON deserialization // </summary> public static T JsonDeserialize <T> (string jsonString) {DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T); MemoryStream MS = new MemoryStream (EncodingUTFGetBytes (jsonString); T obj = (T) serReadObject (MS ); return obj ;}}
Serialization Demo:
Simple Object Person:
public class Person { public string Name { get; set; } public int Age { get; set; } }
Serialized as a JSON string:
Protected void Page_Load (object sender, EventArgs e) {Person p = new Person (); pName = "Zhang San"; pAge = 28; string jsonString = JsonHelperJsonSerializer <Person> (p ); responseWrite (jsonString );}
Output result:
{"Age": 28, "Name": "Zhang San "}
Deserialization Demo:
Protected void Page_Load (object sender, EventArgs e) {string jsonString = "{\" Age \ ": 28, \" Name \ ": \" James \"}"; person p = JsonHelper. jsonDeserialize <Person> (jsonString );}
Running result:
ASP. you can also use JavaScriptSerializer for JSON serialization and deserialization in. NET. web. script. in the Serializatioin namespace, System must be referenced. web. extensions. dll. you can also use JSON. NET.
Iii. Processing of JSON serialization and deserialization Date and Time
JSON format does not support date and time. DateTime value is displayed as a JSON string in the format of "/Date (700000 + 0500)/", where the first number (700000 in the provided example) it is the number of milliseconds that have elapsed since midnight, January 1, January 1, 1970 by normal time (non-timeout. This number can be a negative number to indicate the previous time. The example contains "+ 0500", which indicates that the time belongs to the Local type, that is, it should be converted to the Local time zone during deserialization. If this part does not exist, the time is deserialized to Utc.
Modify the Person class and add LastLoginTime:
public class Person { public string Name { get; set; } public int Age { get; set; } public DateTime LastLoginTime { get; set; } }
Person p = new Person (); p. name = "James"; p. age = 28; p. lastLoginTime = DateTime. now; string jsonString = JsonHelper. jsonSerializer <Person> (p );
Serialization result:
{"Age": 28, "LastLoginTime": "\/Date (1294499956278 + 0800) \/", "Name": "James "}
1. Use a regular expression to replace the regular expression in the background. Modify JsonHelper:
Using System; using SystemCollectionsGeneric; using SystemLinq; using SystemWeb; using SystemRuntimeSerializationJson; using SystemIO; using SystemText; using SystemTextRegularExpressions; /// <summary> /// JSON serialization and deserialization helper class /// </summary> public class JsonHelper {// <summary> // JSON serialization /// </summary> public static string JsonSerializer <T> (T t) {DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T); MemoryStream MS = new MemoryStream (); serWriteObject (MS, t); string jsonString = EncodingUTFGetString (msToArray ()); msClose (); // Replace the Json Date string p = @ "\/Date \ (\ d +) \ + \ d + \)\\/"; matchEvaluator matchEvaluator = new MatchEvaluator (ConvertJsonDateToDateString); Regex reg = new Regex (p); jsonString = regReplace (jsonString, matchEvaluator); return jsonString ;} /// <summary> /// JSON deserialization /// </summary> public static T JsonDeserialize <T> (string jsonString) {// convert the string in the format of "yyyy-MM-dd HHmmss" to "\/Date (1294499956278 + 0800) \/"Format string p = @" \ d {4}-\ d {2}-\ d {2} \ s \ d {2} \ d {2} \ d {2 }"; matchEvaluator matchEvaluator = new MatchEvaluator (generator); Regex reg = new Regex (p); jsonString = regReplace (jsonString, matchEvaluator); DataContractJsonSerializer ser = new generator (typeof (T )); memoryStream MS = new MemoryStream (EncodingUTFGetBytes (jsonString); T obj = (T) serReadObject (MS); return obj ;} /// <summary> // convert the Json serialization time from/Date (1294499956278 + 0800) to a string // </summary> private static string ConvertJsonDateToDateString (Match m) {string result = stringEmpty; DateTime dt = new DateTime (1970,1, 1); dt = dtAddMilliseconds (longParse (mGroups [1] Value); dt = dtToLocalTime (); result = dtToString ("yyyy-MM-dd HHmmss"); return result ;} /// <summary> /// convert the time string to Json time // </summary> private static string ConvertDateStringToJsonDate (Match m) {string result = stringEmpty; dateTime dt = DateTimeParse (mGroups [0] Value); dt = dtToUniversalTime (); TimeSpan ts = dt-DateTimeParse ("1970-01-01 "); result = stringFormat ("\/Date ({0} + 0800) \/", tsTotalMilliseconds); return result ;}}
Serialization Demo:
Person p = new Person (); p. name = "James"; p. age = 28; p. lastLoginTime = DateTime. now; string jsonString = JsonHelper. jsonSerializer <Person> (p );
Running result:
{"Age": 28, "LastLoginTime": "01:00:56", "Name": "James "}
Deserialization Demo:
String json = "{\" Age \ ": 28, \" LastLoginTime \ ": \" 00:30:00 \ ", \" Name \ ": \" James \"}";
P = JsonHelper. JsonDeserialize <Person> (json );
Running result:
The application scope of string replacement in the background is relatively narrow, and it is more difficult to consider the globalization of multiple languages.
2. Processing with JavaScript
function ChangeDateFormat(jsondate) { jsondate = jsondate.replace("/Date(", "").replace(")/", ""); if (jsondate.indexOf("+") > 0) { jsondate = jsondate.substring(0, jsondate.indexOf("+")); } else if (jsondate.indexOf("-") > 0) { jsondate = jsondate.substring(0, jsondate.indexOf("-")); } var date = new Date(parseInt(jsondate, 10)); var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) date.getMonth() + 1; var currentDate = date.getDate() < 10 ? "0" + date.getDate() date.getDate(); return date.getFullYear() + "-" + month + "-" + currentDate; }
Simple Demo:
ChangeDateFormat ("\/Date (1294499956278 + 0800 )\/");
Result:
2011-1-8
4. JSON serialization and deserialization collection, dictionary, and Array Processing
In JSON data, all sets, dictionaries, and arrays are represented as arrays.
List <T> serialization:
List <Person> list = new List <Person> () {new Person () {Name = "James", Age = 28}, new Person () {Name = "", Age = 25 }}; string jsonString = JsonHelper. jsonSerializer <List <Person> (list );
Serialization result:
"[{\" Age \ ": 28, \" Name \ ": \" Zhang San \ "},{ \" Age \ ": 25, \" Name \": \ "Li Si \"}]"
The Dictionary cannot be directly used for JSON. The conversion of a Dictionary into JSON is not in the same format as the original Dictionary. Instead, the Dictionary uses the Key of the Dictionary as the value of the name "Key, use the Value of Dictionary as the Value named "Value. For example:
Dictionary <string, string> dic = new Dictionary <string, string> (); dic. add ("Name", "Zhang San"); dic. add ("Age", "28"); string jsonString = JsonHelper. jsonSerializer <Dictionary <string, string> (dic );
Serialization result:
"[{\" Key \ ": \" Name \ ", \" Value \ ": \" Zhang San \ "},{ \" Key \": \ "Age \", \ "Value \": \ "28 \"}]"
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.