There are more and more scenarios for using JSON in Web applications, and this article describes ASP. NET in the serialization and deserialization of JSON, mainly for JSON simple introduction, ASP. NET how to serialize and deserialize processing, in serialization and deserialization of date time, collection, and dictionary processing.
First, JSON introduction
JSON (JavaScript object Notation,javascript objects notation) is a lightweight data interchange format.
JSON is a collection of "name-value pairs." The structure consists of a brace ' {} ', bracket ' [] ', comma ', ', colon ': ', double quotation mark ' ' ' ' ', ' which contains a data type of object,number,boolean,string,array, NULL, etc.
JSON has the following form:
Object is an unordered set of "name-value pairs" where an object ends with "{" and "}". Each "name" follows a ":" and multiple "name-value pairs" are separated by commas. Such as:
var user={"name": "John", "Gender": "Male", "Birthday": "1980-8-8"}
An array is an ordered set of values, with an array beginning with "[", Ending with "]", and separating values using "." Such as:
var userlist=[{"user": {"name": "John", "Gender": "Male", "Birthday": "1980-8-8"}},{"user": {"name": "Dick", "gender": "Male", " Birthday ":" 1985-5-8 "}}];
A string is a collection of any number of Unicode characters enclosed by double quotes, which is escaped using backslashes.
II. serialization and deserialization of JSON data
You can use the DataContractJsonSerializer class to serialize a type instance to a JSON string and deserialize the JSON string into a type instance. DataContractJsonSerializer under the System.Runtime.Serialization.Json namespace, the. NET Framework 3.5 is included in System.ServiceModel.Web.dll, you need to add a reference to it, the. NET Framework 4 is in System.Runtime.Serialization.
Code that uses DataContractJsonSerializer to serialize and deserialize:
Copy Code code 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 classes
</summary>
public class Jsonhelper
{
<summary>
JSON serialization
</summary>
public static string jsonserializer<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 Code code as follows:
public class Person
{
public string Name {get; set;}
public int Age {get; set;}
}
Serialized as a JSON string:
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
Person p = new person ();
P.name = "John";
P.age = 28;
String jsonstring = Jsonhelper.jsonserializer<person> (p);
Response.Write (jsonstring);
}
Output results:
{"Age": "Name": "John"}
Anti-serialization Demo:
Copy Code code as follows:
protected void Page_Load (object sender, EventArgs e)
{
String jsonstring = "{\ age\": 28,\ "name\": \ "john \"};
Person p = jsonhelper.jsondeserialize<person> (jsonstring);
}
Run Result:
Asp. The JSON serialization and deserialization in net can also use JavaScriptSerializer, System.Web.Script.Serializatioin namespace, you need to refer to System.Web.Extensions.dll. You can also use Json.NET.
Third, JSON serialization and deserialization date-time processing
The JSON format does not support dates and times directly. The datetime value is displayed as a JSON string in the form of "/date (700000+0500)/", where the first digit (700000 in the provided example) is the number of milliseconds in the GMT time zone that have elapsed since midnight of January 1, 1970 (not daylight saving time). The number can be negative to indicate the time before. The example includes a partial optional "+0500", which indicates that the time belongs to the local type, that is, it should be converted to the native time zone when deserializing. Without this part, the time is deserialized to UTC.
Modify the person class to add Lastlogintime:
Copy Code code 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 = "John";
P.age = 28;
P.lastlogintime = DateTime.Now;
String jsonstring = Jsonhelper.jsonserializer<person> (p);
Serialization Result:
{"Age": "Lastlogintime": "\/date (1294499956278+0800) \/", "Name": "John"}
1. Use regular expressions to replace processing in the background. Modify Jsonhelper:
Copy Code code 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 classes
</summary>
public class Jsonhelper
{
<summary>
JSON serialization
</summary>
public static string jsonserializer<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 date string for JSON
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 a string in the format "Yyyy-mm-dd HH:mm:ss" 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>
The time to serialize JSON from/date (1294499956278+0800) to 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 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 Code code as follows:
Person p = new person ();
P.name = "John";
P.age = 28;
P.lastlogintime = DateTime.Now;
String jsonstring = Jsonhelper.jsonserializer<person> (p);
Run Result:
{"Age": "Lastlogintime": "2011-01-09 01:00:56", "Name": "John"}
Anti-serialization Demo:
String json = "{\ age\": 28,\ "lastlogintime\": \ "2011-01-09 00:30:00\", \ "name\": \ "john \"} ";
P=jsonhelper.jsondeserialize<person> (JSON);
Run Result:
Replacement strings in the background are narrower in scope, and can be even more cumbersome to take into account the multiple languages of globalization.
2. Use JavaScript to handle
Copy Code code 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) \/");
Results:
Iv. JSON serialization and deserialization collection, dictionary, array processing
In JSON data, all collections, dictionaries, and arrays are represented as arrays.
List<t> Serialization:
Copy Code code as follows:
list<person> list = new list<person> ()
{
New Person () {name= "John", age=28},
New Person () {name= "Dick", age=25}
};
String jsonstring = Jsonhelper.jsonserializer<list<person>> (List);
Serialization Result:
"[{\" age\ ": 28,\" name\ ": \" john \ "},{\" age\ ": 25,\" name\ ": \" Dick \ "}]"
Dictionaries cannot be used directly in json,dictionary dictionaries to convert to JSON instead of the same format as the original dictionary, but in the form of the dictionary key as the value of the name "key", the value of dictionary as the name "value". Such as:
dictionary<string, string> dic = new dictionary<string, string> ();
Dic. ADD ("Name", "John");
Dic. ADD ("Age", "28");
String jsonstring = Jsonhelper.jsonserializer < Dictionary<string, string>> (DIC);
Serialization Result:
"[{\" key\ ": \" name\ ", \" value\ ": \" john \ "},{\" key\ ": \" age\ ", \" value\ ": \" 28\ "}]"