Asp. The serialization and deserialization of JSON in net

Source: Internet
Author: User
Tags gmt time zone string to json

JSON is a data format designed specifically for JavaScript code that runs on Web pages in a browser. There are more and more scenarios for using JSON in Web site applications, this article describes the serialization and deserialization of JSON in ASP, mainly a brief introduction to JSON, how to process the serialization and deserialization of ASP, and the processing of datetime, set, and dictionary in serialization and deserialization.

I. Introduction of JSON

JSON (JavaScript object Notation,javascript) is a lightweight data interchange format.

JSON is a collection of "name-value pairs". The structure consists of braces ' {} ', brackets ' [] ', comma ', ', ' colon ': ', ' double quotation marks ' "", consisting of 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," and an object ends with "{" Starting with "}". After each "name" followed by a ":", multiple "name value pairs" are separated by commas. Such as:

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

An array is an ordered set of values, an array that begins with "[", Ends with "]", and separates values by ",". Such as:

var userlist=[{"user": {"name": "Zhang San", "gender": "Male", "Birthday": "1980-8-8"}},{"user": {"name": "John Doe", "gender": "Male", " Birthday ":" 1985-5-8 "}}];

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

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 Included in System.ServiceModel.Web.dll, you need to add a reference to it;. NET Framework 4 in System.Runtime.Serialization.

Using DataContractJsonSerializer to serialize and deserialize code:

   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;
   
   9://<summary>
  ///JSON serialization and deserialization helper classes
  One://</summary>
  12:public class Jsonhelper
  13: {
  ///     <summary>
  ://     JSON serialization
  ://     </summary>
  +: Public     static string jsonserializer<t> (T t)
  :     {
  :         datacontractjsonserializer ser = new DataContractJsonSerializer (typeof (T));
  :         MemoryStream ms = new MemoryStream ();
  :         ser. WriteObject (MS, T);
  A:         string jsonstring = Encoding.UTF8.GetString (ms. ToArray ());
  At:         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;
  :     }
  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 = "Zhang San";
   5:     p.age = 28;
   
   7:     String jsonstring = Jsonhelper.jsonserializer<person> (p);
   8:     Response.Write (jsonstring);
   9:}

Output Result:

Deserialization Demo:

   1:protected void Page_Load (object sender, EventArgs e)
   2: {
   3:     String jsonstring = "{\" age\ ": 28,\" name\ ": \" Zhang San \ "}";
   4: Person     p = jsonhelper.jsondeserialize<person> (jsonstring);
   5:}

Operation Result:

Asp. The JSON serialization and deserialization in net can also use JavaScriptSerializer, Under the 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 directly support date and time. The datetime value value is displayed as a JSON string in the form "/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 January 1, 1970, in normal time (non-daylight savings). 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 native time zone when deserializing. If there is no part, the time is deserialized into UTC.

To modify the person class, 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 = "Zhang San";
   3:p.age = 28;
   4:p.lastlogintime = DateTime.Now;
   
   6:string jsonstring = jsonhelper.jsonserializer<person> (p);

Serialization results:

{"Age": "Lastlogintime": "\/date (1294499956278+0800) \", "Name": "Zhang San"}

1, in the background using regular expressions to replace their processing. 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;
   
  ///<summary>
  One:///JSON serialization and deserialization helper classes
  ///</summary>
  13:public class Jsonhelper
  14: {
  ///     <summary>
  ://     JSON serialization
  +//     </summary>
  : public     static string jsonserializer<t> (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 JSON with date string
  :         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)
  PNS:     {
  :         //Convert a string "Yyyy-mm-dd HH:mm:ss" to "\/date (1294499956278+0800) \ \" Format
  A:         string p = @ "\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
  Max:         matchevaluator matchevaluator = new MatchEvaluator (convertdatestringtojsondate);
  A:         regex reg = new regex (p);
  :         jsonstring = Reg. Replace (jsonstring, MatchEvaluator);
  :         datacontractjsonserializer ser = new DataContractJsonSerializer (typeof (T));
  :         MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (jsonstring));
  A:         t obj = (t) ser. ReadObject (MS);
  :         return obj;
  :     }
  
  ///     <summary>
  :     ///Convert JSON serialized time from/date (1294499956278+0800) to string
  Wuyi://     </summary>
  Convertjsondatetodatestring:     private static string (Match m)
  :     {
  Si:         string result = String. Empty;
  :         datetime dt = new DateTime (1970,1,1);
  A:         dt = dt. Addmilliseconds (Long. Parse (M.groups[1]. Value));
  £ º         dt = dt. ToLocalTime ();
  A:         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);
  A:         dt = dt. ToUniversalTime ();
  :         TimeSpan ts = dt-datetime.parse ("1970-01-01");
  :         result = string. Format ("\\/date ({0}+0800) \\/", TS. TotalMilliseconds);
  :         return result;
  :     }
  74:}

Serialization Demo:

   1:person p = new person ();
   2:p.name = "Zhang San";
   3:p.age = 28;
   4:p.lastlogintime = DateTime.Now;
   
   6:string jsonstring = jsonhelper.jsonserializer<person> (p);

Operation Result:

{"Age": "Lastlogintime": "2011-01-09 01:00:56", "Name": "Zhang San"}

Deserialization Demo:

String json = "{\" age\ ": 28,\" lastlogintime\ ": \" 2011-01-09 00:30:00\ ", \" name\ ": \" Zhang San \ "}";
P=jsonhelper.jsondeserialize<person> (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 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:     Else if (Jsondate.indexof ("-") > 0) {
   7:         jsondate = jsondate.substring (0, Jsondate.indexof ("-"));
   8:     }
   
  Ten:     var date = new Date (parseint (Jsondate, 10));
  One:     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;
  14:}

Simple demo:

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

Results:

2011-1-8
Iv. 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<person> List = new List<person> ()
   2: {
   3:     new Person () {name= "Zhang San", age=28},
   4:     new Person () {name= "John Doe", age=25}
   5:};
   
   7:string jsonstring = jsonhelper.jsonserializer<list<person>> (List);

Serialization results:

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

dictionaries cannot be directly used for json,dictionary dictionaries to be converted to JSON instead of the original dictionary format, but in the form of dictionary key as the value of the name "key", with dictionary value as the name " Value ". Such as:

   1:dictionary<string, string> dic = new dictionary<string, string> ();
   2:dic. ADD ("Name", "Zhang San");
   3:dic. ADD ("Age", "28");
   
   5:string jsonstring = Jsonhelper.jsonserializer < Dictionary<string, string>> (DIC);

Serialization results:

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

JSON official website: http://www.json.org/json-zh.html

Standalone JSON serialization: Http://msdn.microsoft.com/zh-cn/library/bb412170.aspx

How to serialize and deserialize JSON: http://msdn.microsoft.com/zh-cn/library/bb412179.aspx

Asp. The serialization and deserialization of JSON in net

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.