Asp. Serialization and deserialization of JSON in net

Source: Internet
Author: User
Tags add date format empty getdate net string string to json

Reading: JSON is a data format designed specifically for JavaScript code running on a Web page in a browser. 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:

1:using System;

2:using System.Collections.Generic;

3:using System.Linq;

4:using system.web;

5:using System.Runtime.Serialization.Json;

6:using System.IO;

7:using System.Text;

8:

9:///<summary>

///JSON serialization and deserialization helper classes

One:///</summary>

12:public class Jsonhelper

13: {

:///<summary>

:///JSON serialization

:///</summary>

17:public static string jsonserializer<t> (t)

18: {

19:datacontractjsonserializer ser = new DataContractJsonSerializer (typeof (T));

20:memorystream ms = new MemoryStream ();

21:ser. WriteObject (MS, T);

22:string jsonstring = Encoding.UTF8.GetString (ms. ToArray ());

23:ms. Close ();

24:return jsonstring;

25:}

26:

:///<summary>

///JSON deserialization

:///</summary>

30:public static T jsondeserialize<t> (String jsonstring)

31: {

32:datacontractjsonserializer ser = new DataContractJsonSerializer (typeof (T));

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

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

35:return obj;

36:}

37:}

Serialization Demo:

Simple Object Person:

1:public class Person

2: {

3:public string Name {get; set;}

4:public int Age {get; set;}

5:}

Serialized as a JSON string:

1:protected void Page_Load (object sender, EventArgs e)

2: {

3:person p = new person ();

4:p.name = "John";

5:p.age = 28;

6:

7:string jsonstring = jsonhelper.jsonserializer<person> (p);

8:response.write (jsonstring);

9:}

Output results:

{"Age": "Name": "John"}

Anti-serialization Demo:

1:protected void Page_Load (object sender, EventArgs e)

2: {

3:string jsonstring = "{\" age\ ": 28,\" name\ ": \" john \ "}";

4:person p = jsonhelper.jsondeserialize<person> (jsonstring);

5:}

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:

1:public class Person

2: {

3:public string Name {get; set;}

4:public int Age {get; set;}

5:public DateTime lastlogintime {get; set;}

6:}

1:person p = new person ();

2:p.name = "John";

3:p.age = 28;

4:p.lastlogintime = DateTime.Now;

5:

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

1:using System;

2:using System.Collections.Generic;

3:using System.Linq;

4:using system.web;

5:using System.Runtime.Serialization.Json;

6:using System.IO;

7:using System.Text;

8:using System.Text.RegularExpressions;

9:

Ten:///<summary>

One:///JSON serialization and deserialization helper classes

///</summary>

13:public class Jsonhelper

14: {

:///<summary>

:///JSON serialization

:///</summary>

18:public static string jsonserializer<t> (t)

19: {

20:datacontractjsonserializer ser = new DataContractJsonSerializer (typeof (T));

21:memorystream ms = new MemoryStream ();

22:ser. WriteObject (MS, T);

23:string jsonstring = Encoding.UTF8.GetString (ms. ToArray ());

24:ms. Close ();

25://Replace JSON date string

26:string p = @ "\\/date\ ((\d+) \+\d+\) \\/";

27:matchevaluator matchevaluator = new MatchEvaluator (convertjsondatetodatestring);

28:regex reg = new Regex (p);

29:jsonstring = Reg. Replace (jsonstring, MatchEvaluator);

30:return jsonstring;

31:}

32:

:///<summary>

:///JSON deserialization

£///</summary>

36:public static T jsondeserialize<t> (String jsonstring)

37: {

38:///convert "YYYY-MM-DD HH:mm:ss" format string 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:regex reg = new Regex (p);

42:jsonstring = Reg. Replace (jsonstring, MatchEvaluator);

43:datacontractjsonserializer ser = new DataContractJsonSerializer (typeof (T));

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

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

46:return obj;

47:}

48:

:///<summary>

50:///The time of JSON serialization from/date (1294499956278+0800) to string

Wuyi:///</summary>

52:private static string convertjsondatetodatestring (Match m)

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-mm-dd HH:mm:ss");

59:return result;

60:}

61:

:///<summary>

63:///Convert time string to JSON time

£///</summary>

65:private static string Convertdatestringtojsondate (Match m)

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

1:person p = new person ();

2:p.name = "John";

3:p.age = 28;

4:p.lastlogintime = DateTime.Now;

5:

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

1:function Changedateformat (jsondate) {

2:jsondate = Jsondate.replace ("/date", ""). Replace (")/", "");

3:if (Jsondate.indexof ("+") > 0) {

4:jsondate = jsondate.substring (0, Jsondate.indexof ("+"));

5:}

6:else if (Jsondate.indexof ("-") > 0) {

7:jsondate = jsondate.substring (0, Jsondate.indexof ("-"));

8:}

9:

10:var date = new Date (parseint (Jsondate, 10));

11:var month = Date.getmonth () + 1 < 10? "0" + (date.getmonth () + 1): Date.getmonth () + 1;

12:var currentdate = date.getdate () < 10? "0" + date.getdate (): Date.getdate ();

13:return date.getfullyear () + "-" + month + "-" + currentdate;

14:}

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:

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

2: {

3:new person () {name= "John", age=28},

4:new person () {name= "Dick", age=25}

5:};

6:

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

1:dictionary<string, string> dic = new dictionary<string, string> ();

2:dic. ADD ("Name", "John");

3:dic. ADD ("Age", "28");

4:

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

Serialization Result:

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

(Source: Blog Park )



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.