Introduction: JSON is a data format specially designed for JavaScript code running on web pages in browsers. There are more and more scenarios where JSON is used in website applications. This article introduces the serialization and decoding of JSON in ASP.NET. Serialization, mainly a brief introduction to JSON, how ASP.NET serializes and deserializes, and how to handle date and time, collections, and dictionaries in serialization and deserialization.
1. Introduction to JSON
JSON (JavaScript Object Notation, JavaScript Object Notation) is a lightweight data exchange format.
JSON is a collection structure of "name-value pairs" consisting of curly brackets "{}", square brackets "[]", commas ",", and colons. ":" is composed of double quotes '", "', and the included data types include objects, numbers, Boolean values, string arrays, NULL, etc.
JSON has the following form:
Object (object) is an unordered collection of "name-value pairs". An object starts with "{" and ends with "}". Each "name" is followed by a ":", Multiple "name-value pairs" are separated by commas, such as:
VAR user = {"Name": "Zhang San", "Gender": "Male", "Birthday": "August 8, 1980"}
An array (array) is an ordered collection of values. An array starts with "[" and ends with "]". The values are separated by "," such as:
VAR user list = [{"user":{"name ": "Zhang San", "Gender": "Male", "Birthday": "August 8, 1980"}}, {"User": {"Name" "Li Si", "Gender": "Male" ","birthday":"May 8, 1985"}}];
A string (string) is a collection of any number of Unicode characters surrounded by double quotes, using backslash escapes.
Second, serialize and deserialize JSON data
You can use the DataContractJsonSerializer class to serialize type instances into JSON strings and deserialize JSON strings into type instances. DataContractJsonSerializer is under the System.Runtime.Serialization.Json namespace. .NET Framework 3.5 is included in the System.ServiceModel.Web .dll file, and a reference to it needs to be added; .NET Framework 4 is in System.Runtime.Serialization.
Using DataContractJsonSerializer serialization and deserialization code:
1: Using System;
2: Using System.Collections.Generic;
3: Using System.Linq;
4: Using System.Web ;
5: Use System.Runtime.Serialization.Json;
6: Use System.IO;
7: Use System.Text;
8:
9: ///
10:/// JSON serialization and deserialization helper class
11:///
12: Public class JsonHelper
13: {
14:/// 15: /// JSON Serialization 16: ///
17: Public static string JsonSerializer
18: {
19: DataContractJsonSerializer Ser = new DataContractJsonSerializer(typeof(T));
20: MemoryStream milliseconds = new MemoryStream();
21: ser.WriteObject(MS, T);
22: String jsonString = Encoding.UTF8 .GetString(ms.ToArray());
23: ms.Close();
24: Return jsonString;
25:}
26:
27:///
28:/// JSON deserialization
29:///
30: Public static JsonDeserialize
31: {
32: DataContractJsonSerializer SER = new DataContractJsonSerializer(typeof(T));
33: MemoryStream milliseconds = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
34: T obj = (T)ser.ReadObject(MS) ;
35: Return OBJ;
36: }
37: }
Serialization demonstration:
Simple object Person:
1: Public class Person
2: {
3: Public string Name {; Group; }
4: Public Interpretation Age {Get; Group; }
5: }
Serialized to JSON string:
1: Protect invalid Page_Load(object sender, EventArgs sent )
2: {
3: Person p = new Person();
4: p.Name = "Zhang San";
5: p.Age = 28;
6:
7: String jsonString = JsonHelper.JsonSerializer
8: Reply to (jsonString);
9: }
Output result:
{"era": 28th, "name": "Zhang San"}
Deserialization demonstration:
1: Protect invalid Page_Load (object sender, EventArgs sent)
2: {
3: String jsonString = "{"age": 28 Day, "name": "Zhang San"}";
4 people P = JsonHelper.JsonDeserialize (jsonString);
5:}
Running results:
JSON serialization and deserialization in ASP.NET can also use JavaScriptSerializer, in System. In the Web.Script.Serializatioin namespace, System.Web.Extensions.dll needs to be referenced. JSON.NET can also be used.
Three, JSON serialization and deserialization date and time processing
JSON format does not directly support date and time. The DateTime value is displayed as a JSON string in the form of "/Date (700000 + 0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone that have elapsed in normal time (not daylight saving time) since midnight on January 1, 1970. The number can be negative to represent a previous time. The optional part of the example including "0500" indicates that the time is of local type, i.e. it should be converted to the local time zone when deserialized. Without that part, the time will be deserialized to UTC.
Modify the personal class and add LastLoginTime:
1: Public class Person
2: {
3: Public string name {; group; }
4: Public interpretation age {get; group; }
5 : public DateTime LastLoginTime {get; group; }
6:}
1: person p = new Person();
2: p.Name = "张三";
3: p.Age = 28;
4: p.LastLoginTime = DateTime.Now;
5:
6: String jsonString = JsonHelper.JsonSerializer (P);
Serialization result:
{"Era" : 28th, "LastLoginTime": "/Date (1294499956278 + 0800) /", "Name": "Zhang San"}
1. Use regular expressions in the background to modify its replacement processing JsonHelper:
1: Use System;
2: Use System.Collections.Generic;
3: Use System.Linq;
4: Use System.Web;
5: Use System.Runtime.Serialization.Json;
6: Using System.IO;
7: Using System.Text;
8: Using System.Text.RegularExpressions;
9:
10:///
11:/// JSON sequence 12: ///
13: Public class JsonHelper
14: {
15: ///
16: // /JSON Serialization
17: ///
18: Public static string JsonSerializer
19: {
20: DataContractJsonSerializer SER = new DataContractJsonSerializer(typeof operation (T));
21: MemoryStream milliseconds = new MemoryStream();
22: ser.WriteObject(MS, T);
23: String jsonString = Encoding.UTF8.GetString(ms.ToArray( ));
24: ms.Close();
25: //Replacement of Json date string
26: String P = @"\/Date ((D+)+D+)\/" ;
27: MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
28: Regular expression chapter = new regular expression (P);
29: jsonString = reg.Replace(jsonString, matchEvaluator);
30 : Return jsonString;
31:}
32:
33:///
34:/// JSON deserialization
35:///
36: Public static JsonDeserialize
37: {
38: //Convert the string in the format of "YYYY-MM-DD HH:MM:SS" to "/Date ( 1294499956278 + 0800) /"Format
39: String P = @" D {4} - d {2} - d {2} S D {2}: D {2}: D {2}";
40: MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
41: Regular Expression Chapter = new Regular Expression (P);
42: jsonString = reg.Replace(jsonString, matchEvaluator);
43: DataContractJsonSerializer SER = new DataContractJsonSerializer(typeof(T));
44: MemoryStream milliseconds = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
45: T obj = (T)ser.ReadObject(MS);
46: Return to OBJ;
47:}
48:
49:///
50: ///Convert Json serialization time by /date (1294499956278 + 0800) for string
51:///
52: private static string ConvertJsonDateToDateString(semi) 53: {
54: String result = String.Empty;
55 :DateTime dt = new DateTime(1970,1,1);
56: DT = dt.AddMilliseconds(long.Parse(m.Groups[1].value));
57: DT = dt.ToLocalTime();
58: Result = dt.ToString("YYYY- DD Time to convert to Json
64: ///
65: Private static string ConvertDateStringToJsonDate (semi)
66: {
67: String result = String.Empty;
68: DateTime DT = DateTime.Parse(m.Groups[0].value);
69: DT = dt.ToUniversalTime();
70: Timespan TS = DT - DateTime.Parse("1970 -01-01");
71: result = String.Format("\/Date({0}+0800)\/", ts.TotalMilliseconds);
72: Return result;
73:}
74:}
Serialization demonstration:
1: Person p = new Person();
2: p.Name = "Zhang San";
3: p.Age = 28;
4 : p.LastLoginTime = DateTime.Now;
5:
6: String jsonString = JsonHelper.JsonSerializer
Run result:
{"Era": 28th, "LastLoginTime" ": "2011-01-09 one o'clock minute 56 seconds", "Name": "Zhang San"}
Deserialization demo:
JSON string = "{"Age": 28th,"LastLoginTime" :"2011-01-09 00:30:00","Name":"Zhang San"}";
P = JsonHelper.JsonDeserialize (JSON);
Running result:
in the background The scope of replacement strings is relatively narrow, and it will be more troublesome if you consider the multiple languages of globalization.
2. Utilize JavaScript processing
1: Function ChangeDateFormat(jsondate) {
2: jsondate = jsondate.replace("/date(","").replace(")/","");
3: If (jsondate.indexOf ("+") > 0) {
4: jsondate = jsondate.substring (0, jsondate.indexOf ("+"));
5: }
6: Otherwise if (jsondate.indexOf("-")> 0) {
7: jsondate = jsondate.substring(0, jsondate.indexOf("-"));
8:}
9:
10: VAR date = new date(parseInt function(jsondate, 10));
11: var month = date.getMonth() + 1
12: VAR's currentdate = date.getDate()
13: Return date.getFullYear() + "-" + month + "-" + currentdate;
14: }
Simple demonstration:
ChangeDateFormat("/Date(1294499956278+0800)/");
Results:
Four, JSON serialization and deserialization processing of collections, dictionaries, arrays
In JSON data, all collections, dictionaries and arrays are both represented as arrays.
List
1: List
2: {
3: New Person() {name=" Zhang San", age = 28},
4: new Person() {name = "李思", age = 25}
5: };
6:
7: String jsonString = JsonHelper. JsonSerializer >(List);
Serialization result:
"[{"Age": 28,"Name":"Zhang San"},{"Age": 25, "Name": "李思"}]"
Dictionaries cannot be used directly in JSON. The conversion of a dictionary into JSON is not consistent with the original dictionary format, but uses the dictionary keys as the value of the name "key". Use the value of the dictionary as the value named "value". Such as:
1: Dictionary
2: dic.Add("Name", "Zhang San");
3: dic.Add("Era", "28");
4:
5: String jsonString = JsonHelper.JsonSerializer
Serialization result:
1: "[{"key": "name", "value": "Zhang San"}, {"key": "age", "value": "28"}]"

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools