Asp. The serialization and deserialization of JSON in net

Source: Internet
Author: User
Tags gmt time zone local time
Guidance: JSON is a data format designed specifically for JavaScript code that runs on Web pages in a browser, and more and more scenes are being used in Web applications, This article describes the serialization and deserialization of JSON in ASP, mainly a brief introduction to JSON, how to process ASP, serialization and deserialization, the processing of datetime, set, and dictionary in serialization and deserialization.

One, Introduction to JSON

JSON (JavaScript Object notation, JavaScript Object notation) is a lightweight data interchange format.

JSON is the "name value pair" of the collection structure by curly braces "{}" in brackets "[]", "comma", ", colon." ":" Double quotes ' "," ' consists of data types that contain objects, numbers, Boolean values, string arrays, NULL, and so on.

JSON has the following form:

An object (object) is an unordered set of "name-value pairs," with an object starting with "{", "}" ending each "name" followed by a ":", and multiple "name value pairs" separated by commas such as:

var user = {"name": "Zhang San", "gender": "Male", "Birthday": "August 8, 1980"}

An array (array) is an ordered set of values, an array that begins with "[", Ends with "]", and uses "," to separate values such as:

var user list = [{"User": {"name": "Zhang San", "gender": "Male", "Birthday": "August 8, 1980"}},{"user": {"name" "John Doe", "gender": "Male", "Birthday": "May 8, 1985"}}];

A string (string) is a collection of any number of Unicode characters surrounded by double quotation marks, escaped with a backslash.

Second, 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 contained in SYSTEM.SERVICEMODEL.WEB. DLL file, you need to add a reference to it;. NET Framework 4 is in System.Runtime.Serialization.

Using DataContractJsonSerializer to serialize and deserialize code:

1: Use the system;

2: Use System.Collections.Generic;

3: Use of system.linq;

4: Use of system.web;

5: Use System.Runtime.Serialization.Json;

6: Use System.IO;

7: Use System.Text;

8:

9:///< abstracts >

10:///JSON serialization and deserialization helper classes

11:///</Abstract >

12: public class Jsonhelper

13:{

14:///< abstracts >

15:///JSON serialization

16:///</Abstract >

17: public static string Jsonserializer <T> (T t)

18:{

19:datacontractjsonserializer SER = new DataContractJsonSerializer (typeof operation (T));

20:memorystream milliseconds = new MemoryStream ();

21:ser. WriteObject (ms,t);

22: String jsonstring = Encoding.UTF8.GetString (Ms.toarray ());

23:ms. Close ();

24: Return to jsonstring;

25:}

26:

27:///< abstracts >

28:///JSON deserialization

29:///</Abstract >

30: public static Jsondeserialize <T> (String jsonstring)

31:{

32:datacontractjsonserializer SER = new DataContractJsonSerializer (typeof operation (T));

33:memorystream milliseconds = new MemoryStream (Encoding.UTF8.GetBytes (jsonstring));

34:t has obj = (T) ser.readobject (MS);

35: Return to obj;

36:}

37:}

Serialization Demo:

Simple objects for people:

1: public class person

2:{

3: public string name {; group;}

4: Public interpretation of age {fix; group;}

5:}

Serialized as a JSON string:

1: Protect invalid Page_Load (object sender, EventArgs send)

2:{

3: Man p = new person ();

4:p. Name = "Zhang San";

5:p. Age = 28;

6:

7: String jsonstring = Jsonhelper.jsonserializer < people > (P);

8: Reply to (jsonstring);

9:}

Output Result:

{"Time": 28th, "name": "Zhang San"}

Deserialization Demo:

1: Protect invalid Page_Load (object sender, EventArgs send)

2:{

3: String jsonstring = "{\" age \ ": 28th, \" name \ ": \" Zhang San \ "}";

4 people p = Jsonhelper.jsondeserialize < people > (jsonstring);

5:}

Operation Result:

Asp. NET JSON serialization and deserialization can also be used by the JavaScriptSerializer, Under the System.Web.Script.Serializatioin namespace, reference System.Web.Extensions.dll is required. You can also use Json.NET.

Third, JSON serialization and deserialization of date-time processing

The JSON format does not directly support date and time. The datetime value value is displayed as a JSON string in the form "/date (700000 + 0500)/" The first number (700000 in the example provided) is the number of milliseconds in the GMT time zone that have elapsed since midnight January 1, 1970, at normal times (not daylight saving time). The number can be negative to indicate the previous time. The part of the example that includes "0500" is optional, which indicates that the time belongs to the local type, that is, it should be converted to the local time zone when deserializing. If there is no part, the time is deserialized into UTC.

To modify a personal class, add Lastlogintime:

1: public class person

2:{

3: public string name {; group;}

4: Public interpretation of age {fix; group;}

5: Public datetime lastlogintime {fix; group;}

6:}

1: Man p = new person ();

2:p. Name = "Zhang San";

3:p. Age = 28;

4:p. Lastlogintime = DateTime.Now;

5:

6: String jsonstring = Jsonhelper.jsonserializer < people > (P);

Serialization results:

{"Times": 28th, "lastlogintime": "\/Date (1294499956278 + 0800) \/", "name": "Zhang San"}

1. Use regular expressions in the background to replace them with Jsonhelper:

1: Use the system;

2: Use System.Collections.Generic;

3: Use of system.linq;

4: Use of system.web;

5: Use System.Runtime.Serialization.Json;

6: Use System.IO;

7: Use System.Text;

8: Use System.Text.RegularExpressions;

9:

10:///< abstracts >

11:///JSON serialization and deserialization helper classes

12:///</Abstract >

13: public class Jsonhelper

14:{

15:///< abstracts >

16:///JSON serialization

17:///</Abstract >

18: public static string Jsonserializer <T> (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://the date string of the JSON that was replaced

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 to jsonstring;

31:}

32:

33:///< abstracts >

34:///JSON deserialization

35:///</Abstract >

36: public static Jsondeserialize <T> (String jsonstring)

37:{

38://Convert a string "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 operation (T));

44:memorystream milliseconds = new MemoryStream (Encoding.UTF8.GetBytes (jsonstring));

45:t has obj = (T) ser.readobject (MS);

46: Return to obj;

47:}

48:

49:///< abstracts >

50:///convert JSON serialization time by/date (1294499956278 + 0800) to string

51:///</Abstract >

52: private static string convertjsondatetodatestring (Semikron)

53:{

54: String.Empty of string result =;

55:datetime dt = new Date Time (1970,1,1);

56:dt = DT. Addmilliseconds (Long.parse (m.groups [1]. Value));

57:dt = DT. ToLocalTime ();

58: result = dt. ToString ("Yyyy-mm-dd HH:MM:SS");

59: Return the result;

60:}

61:

62:///< abstracts >

63:///time the time string is converted to JSON

64:///</Abstract >

65: private static string Convertdatestringtojsondate (Semikron)

66:{

67: String.Empty of string result =;

DT of the 68:datetime = DateTime.Parse (m.groups [0]. Value);

69:dt = DT. ToUniversalTime ();

70: Time span ts = dt-datetime.parse ("1970-01-01");

71: result = String.Format ("\ \/Date ({0} +0800) \ \", TS. TotalMilliseconds);

72: Return the result;

73:}

74:}

Serialization Demo:

1: Man p = new person ();

2:p. Name = "Zhang San";

3:p. Age = 28;

4:p. Lastlogintime = DateTime.Now;

5:

6: String jsonstring = Jsonhelper.jsonserializer < people > (P);

Operation Result:

{"Times": 28th, "Lastlogintime": "2011-01-09 1:00 56 sec", "name": "Zhang San"}

Deserialization Demo:

JSON string = "{\" age \ ": 28th, \" lastlogintime \ ": \" 2011-01-09 00:30:00 \ ", \" name \ ": \" Zhang San \ "}";

P = Jsonhelper.jsondeserialize < people > (JSON);

Operation Result:

Replacing strings in the background is narrower, and more cumbersome if you take into account the globalization of multiple languages.

2. Using JavaScript for 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: Reactive ONE months = 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 demo:

Changedateformat ("\/date (1294499956278 + 0800) \/");

Results:

Four, JSON serialization and deserialization of collections, dictionaries, arrays of processing

In JSON data, all collections, dictionaries, and arrays are represented as arrays.

List <T> Serialization:

1: List < people > list = new List < people > ()

2:{

3: New Person () {name = "Zhang San", age = 28},

4: New Person () {name = "John Doe", age = 25}

5:};

6:

7: String jsonstring = Jsonhelper.jsonserializer < List < people >> (list);

Serialization results:

"[{\" Age \ ": 28th, \" name \ ": \" Zhang San \ "},{\" Age \ ": 25,\" name \ ": \" john Doe \ "}]"

Dictionaries cannot be used directly in JSON, and dictionary dictionaries are converted to JSON instead of the original dictionary format, but rather as the dictionary's key as the name "key" value, with the value of the dictionary as the value of the name "value". Such as:

1: Dictionary < string, string > DIC = new Dictionary < string, string > ();

2:dic. ADD ("name", "Zhang San");

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

4:

5: String jsonstring = Jsonhelper.jsonserializer < Dictionary < string, string >> (DIC);

Serialization results:

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

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.