Instructions for the serialization and deserialization of JSON in ASP.NET

  • 2020-05-12 02:31:26
  • OfStack

This article introduces the serialization and deserialization of JSON in ASP.NET. It mainly introduces the simple processing of JSON, how to serialize and deserialize ASP.NET, and how to serialize and deserialize the date, time, collection and dictionary.
1. JSON profile
JSON(JavaScript Object Notation,JavaScript object notation) is a lightweight data interchange format.
JSON is a collection of name-value pairs. Structure by the curly braces {}, brackets' [] 'comma', ', a colon ':', '" "' of the quotes, include data types have Object, Number, Boolean, String, Array, NULL, etc.
JSON has the following forms:
The object (Object) is an unordered collection of name-value pairs, with an object beginning with "{" and ending with"} ". Each name is followed by 1:, and multiple name-value pairs are separated by commas. Such as:
var user = {" name ":" 3 ", "gender" : "male" and "birthday" : "1980-8-8"}
An array (Array) is an ordered collection of values. An array begins with "[" and ends with"] ", separated by ", ". Such as:
var userlist = [{" user ": {" name" : "3", "gender" : "male" and "birthday" : "1980-8-8"}}, {" user ": {" name" : "4" lee, "gender" : "male" and "birthday" : "1985-5-8"}}].
A string (String) is a collection of any number of Unicode characters surrounded by double quotes, escaped using a backslash.
2. Serialize and deserialize JSON data
You can use the DataContractJsonSerializer class to serialize a type instance to an JSON string and deserialize an JSON string to a type instance. DataContractJsonSerializer in System. Runtime. Serialization. Under Json namespace. NET Framework. 3.5 included in System ServiceModel. Web. dll, you need to add a reference to its; .NET Framework 4 in System.Runtime.Serialization.
Use DataContractJsonSerializer to serialize and deserialize the code:
 
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 Serialize and deserialize secondary classes  
/// </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; 
} 
} 

Serialize Demo:
Simple object Person:
 
public class Person 
{ 
public string Name { get; set; } 
public int Age { get; set; } 
} 

Serialized as JSON string:
 
protected void Page_Load(object sender, EventArgs e) 
{ 
Person p = new Person(); 
p.Name = " zhang 3"; 
p.Age = 28; 
string jsonString = JsonHelper.JsonSerializer<Person>(p); 
Response.Write(jsonString); 
} 

Output results:
{" Age ": 28," Name ":" 3 "}
Deserialize Demo:
 
protected void Page_Load(object sender, EventArgs e) 
{ 
string jsonString = "{\"Age\":28,\"Name\":\" zhang 3\"}"; 
Person p = JsonHelper.JsonDeserialize<Person>(jsonString); 
} 

Operation results:
ASP. NET JSON of serialization and deserialization can also use JavaScriptSerializer, in System. Web. Script. Serializatioin namespace, need to quote System. Web. Extensions. dll. You can also use JSON. NET.
3. Processing of JSON serialization and deserialization date and time
The JSON format does not directly support dates and times. The DateTime value is shown as an JSON string in the form "/Date(700,000 +0500)/", where the first number (700,000 in the submitted example) is the number of milliseconds in the GMT time zone that have passed in normal time (non-daylight saving time) since midnight on January 1, 1970. The number can be negative to indicate the time before. The optional part of the example that includes "+0500" indicates that the time is of type Local, which means that it should be converted to a local time zone when deserialized. Without this section, the time is deserialized to Utc.
Modify Person class, 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 = " zhang 3"; 
p.Age = 28; 
p.LastLoginTime = DateTime.Now; 
string jsonString = JsonHelper.JsonSerializer<Person>(p); 

Serialization results:
{" Age ": 28," LastLoginTime ":" \ / Date (1294499956278 + 0800) \ / ", "Name" : "3"}
1. Use regular expressions to replace them in the background. Modify JsonHelper:
 
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 Serialize and deserialize secondary classes  
/// </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 Json the 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) 
{ 
// will "yyyy-MM-dd HH:mm:ss" Format of the string to "\/Date(1294499956278+0800)\/" format  
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> 
///  will Json Serialization time by /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> 
///  Converts 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:
 
Person p = new Person(); 
p.Name = " zhang 3"; 
p.Age = 28; 
p.LastLoginTime = DateTime.Now; 
string jsonString = JsonHelper.JsonSerializer<Person>(p); 

Operation results:
{" Age ": 28," LastLoginTime ":" the 2011-01-09 01:00:56 ", "Name" : "3"}
Deserialize Demo:
string json = "{28, \" Age \ ": \" LastLoginTime \ ": \" the 2011-01-09 00:30:00 \ ", \ "Name \" : \ "zhang 3 \"} ";
p=JsonHelper.JsonDeserialize < Person > (json);
Operation results:
Replacing strings in the background is a narrow application, especially if you consider the globalization of multiple languages.
2. Use 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)\/");
Results:
4. JSON serialization and deserialization of collections, dictionaries and arrays
In JSON data, all collections, dictionaries, and arrays are represented as arrays.
List < T > Serialization:
 
List<Person> list = new List<Person>() 
{ 
new Person(){ Name=" zhang 3", Age=28}, 
new Person(){ Name=" li 4", Age=25} 
}; 
string jsonString = JsonHelper.JsonSerializer<List<Person>>(list); 

Serialization results:
"[{28, \" Age \ ": \" Name \ ": \ \" zhang 3 "}, {\ "Age \" : 25, \ "Name \" : \ "li 4 \}"]"
Dictionaries cannot be used directly for JSON. Dictionary dictionaries are converted to JSON not in accordance with the original dictionary format 1, but in the form of Dictionary Key as the value of the name "Key" and Value Dictionary as the value of the name "Value". Such as:
Dictionary < string, string > dic = new Dictionary < string, string > ();
dic. Add (" Name ", "3");
dic.Add("Age", "28");
string jsonString = JsonHelper.JsonSerializer < Dictionary < string, string > > (dic);
Serialization results:
"[{\" Key \ ": \" Name \ ", \ "Value \" : \ \ "zhang 3"}, {\ "Key \" : \ "Age \", \ "Value \" : \ "and \"}]"

Related articles: