Serialization and deserialization of JSON in ASP.NET

巴扎黑
Release: 2016-12-20 09:12:56
Original
1225 people have browsed it

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:///

;< p>>

15: /// JSON Serialization

16: ///

17: Public static string JsonSerializer (T T)

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 (string jsonString)

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 (P);

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 (T T)

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 (string jsonString)

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 (P);

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 <10? "0" + (date.getMonth() + 1): date.getMonth() + 1;

12: VAR's currentdate = date.getDate() < 10? "0" + date.getDate(): 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 Serialization:

1: List List = new 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 DIC = New Dictionary ();

2: dic.Add("Name", "Zhang San");

3: dic.Add("Era", "28");

4:

5: String jsonString = JsonHelper.JsonSerializer >(DIC);

Serialization result:

1: "[{"key": "name", "value": "Zhang San"}, {"key": "age", "value": "28"}]"

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!