More and more scenarios are using JSON in website applications. This article introduces ASP. net json serialization and deserialization, mainly a brief introduction to JSON, ASP.. NET how to serialize and deserialize the processing of date, set, and dictionary in serialization and deserialization.
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 System. runtime. serialization. in the Json namespace ,. NET Framework 3.5 is included in System. serviceModel. web. dll, you need to add a reference to it ;. NET Framework 4 in the System. runtime. serialization.
Code for serialization and deserialization using DataContractJsonSerializer:
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. IO;
Using System. Text;
/// <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 ();
Ser. WriteObject (MS, t );
String jsonString = Encoding. UTF8.GetString (ms. ToArray ());
Ms. Close ();
Return jsonString;
}
/// <Summary>
/// JSON deserialization
/// </Summary>
Public static T JsonDeserialize <T> (string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T ));
MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (jsonString ));
T obj = (T) ser. ReadObject (MS );
Return obj;
}
}
Serialization Demo:
Simple Object Person:Copy codeThe Code is as follows: public class Person
{
Public string Name {get; set ;}
Public int Age {get; set ;}
}
Serialized as a JSON string:Copy codeThe Code is as follows: protected void Page_Load (object sender, EventArgs e)
{
Person p = new Person ();
P. Name = "James ";
P. Age = 28;
String jsonString = JsonHelper. JsonSerializer <Person> (p );
Response. Write (jsonString );
}
Output result:
{"Age": 28, "Name": "Zhang San "}
Deserialization Demo:Copy codeThe Code is as follows: 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. The DateTime value is displayed as a JSON string in the format of "/Date (700000 + 0500)/", where the first number (700000 In the example provided) 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:Copy codeThe Code is as follows: 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: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. IO;
Using System. Text;
Using System. Text. RegularExpressions;
/// <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 ();
Ser. WriteObject (MS, t );
String jsonString = Encoding. UTF8.GetString (ms. ToArray ());
Ms. Close ();
// Replace the Json Date string
String p = @ "\/Date \ (\ d +) \ + \ d + \)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator (ConvertJsonDateToDateString );
Regex reg = new Regex (p );
JsonString = reg. Replace (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 HH: mm: ss" to "\/Date (1294499956278 + 0800) \/".
String p = @ "\ d {4}-\ d {2}-\ d {2} \ s \ d {2 }:\ d {2 }: \ d {2 }";
MatchEvaluator matchEvaluator = new MatchEvaluator (ConvertDateStringToJsonDate );
Regex reg = new Regex (p );
JsonString = reg. Replace (jsonString, matchEvaluator );
DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T ));
MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (jsonString ));
T obj = (T) ser. ReadObject (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 = string. Empty;
DateTime dt = new DateTime (1970, 1, 1 );
Dt = dt. AddMilliseconds (long. Parse (m. Groups [1]. Value ));
Dt = dt. ToLocalTime ();
Result = dt. ToString ("yyyy-MM-dd HH: mm: ss ");
Return result;
}
/// <Summary>
/// Convert the time string to Json time
/// </Summary>
Private static string ConvertDateStringToJsonDate (Match m)
{
String result = string. Empty;
DateTime dt = DateTime. Parse (m. Groups [0]. Value );
Dt = dt. ToUniversalTime ();
TimeSpan ts = dt-DateTime. Parse ("1970-01-01 ");
Result = string. Format ("\/Date ({0} + 0800) \/", ts. TotalMilliseconds );
Return result;
}
}
Serialization Demo:Copy codeThe Code is as follows: 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 JavaScriptCopy codeThe Code is as follows: 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:
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:Copy codeThe Code is as follows: List <Person> list = new List <Person> ()
{
New Person () {Name = "James", Age = 28 },
New Person () {Name = "Li Si", 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", "James ");
Dic. Add ("Age", "28 ");
String jsonString = JsonHelper. JsonSerializer <Dictionary <string, string> (dic );
Serialization result:
"[{\" Key \ ": \" Name \ ", \" Value \ ": \" Zhang San \ "},{ \" Key \": \ "Age \", \ "Value \": \ "28 \"}]"