How to serialize and deserialize JSON in the ASPNET method _ Practical Tips

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

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 Systemruntimeserializationjson namespace, NET Framework 5 is included in the Systemservicemodelwebdll, You need to add a reference to it; NET Framework 4 is in systemruntimeserialization.

Code that uses DataContractJsonSerializer to serialize and deserialize:

Using System;
Using Systemcollectionsgeneric;
Using Systemlinq;
Using Systemweb;
Using Systemruntimeserializationjson;
Using Systemio;
 Using Systemtext; <summary>///JSON serialization and deserialization auxiliary class///</summary> public class Jsonhelper {///<summary>///jso  N Serialization///</summary> public static string jsonserializer<t> (T t) {DataContractJsonSerializer ser
     = new DataContractJsonSerializer (typeof (T));
     MemoryStream ms = new MemoryStream ();
     Serwriteobject (MS, T);
     String jsonstring = Encodingutfgetstring (Mstoarray ());
     Msclose ();
   return jsonstring; ///<summary>///JSON deserialization///</summary> public static T jsondeserialize<t> (String jsons
     Tring) {DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T));
     MemoryStream ms = new MemoryStream (encodingutfgetbytes (jsonstring));
     T obj = (t) serreadobject (MS);
   return obj; }
 }

Serialization Demo:

Simple Object Person:

   public class person
 {public
   string Name {get; set;}
   public int Age {get; set;}
 }

Serialized as a JSON string:

 protected void Page_Load (object sender, EventArgs e)
{person
  p = new Person ();
  PName = "John";
   PAge =; 
  String jsonstring = Jsonhelperjsonserializer<person> (p);
   Responsewrite (jsonstring);
 }

Output results:

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

Anti-serialization Demo:

   protected void Page_Load (object sender, EventArgs e)
{
   string jsonstring = "{\ age\": 28,\ "name\": \ "john \"}; C16/>person p = jsonhelper.jsondeserialize<person> (jsonstring);
}

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

   public class person
 {public
  string Name {get; set;}
   public int Age {get; set;}
   Public DateTime lastlogintime {get; set;}
 }
 Person p = new person ();
 P.name = "John";
 P.age =;
 P.lastlogintime = DateTime.Now; 
 String jsonstring = Jsonhelper.jsonserializer<person> (p);

Serialization Result:

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

1, in the background using regular expressions to replace the processing. Modify Jsonhelper:

   Using System;
  Using Systemcollectionsgeneric;
  Using Systemlinq;
  Using Systemweb;
  Using Systemruntimeserializationjson;
  Using Systemio;
  Using Systemtext;
   
  Using Systemtextregularexpressions;
    &lt;summary&gt;///JSON serialization and deserialization auxiliary class///&lt;/summary&gt; public class Jsonhelper {///&lt;summary&gt; JSON serialization///&lt;/summary&gt; public static string jsonserializer&lt;t&gt; (T t) {Datacontractjsonse
      Rializer ser = new DataContractJsonSerializer (typeof (T));
      MemoryStream ms = new MemoryStream ();
      Serwriteobject (MS, T);
      String jsonstring = Encodingutfgetstring (Mstoarray ());
      Msclose ();
      Replace the Date string of JSON with string p = @ "\\/date\ ((\d+) \+\d+\) \\/";
      MatchEvaluator matchevaluator = new MatchEvaluator (convertjsondatetodatestring);
      Regex reg = new regex (p);
      jsonstring = Regreplace (jsonstring, MatchEvaluator);
    return jsonstring; }///&lt;summary&gt;///json deserialization///&lt;/summary&gt; public static T jsondeserialize&lt;t&gt; (string jsonstring) {//convert string "yyyy-mm-dd HHMMSS" format to "\/
      Date (1294499956278+0800) \/"format string p = @" \d{4}-\d{2}-\d{2}\s\d{2}\d{2}\d{2} ";
      MatchEvaluator matchevaluator = new MatchEvaluator (convertdatestringtojsondate);
      Regex reg = new regex (p);
      jsonstring = Regreplace (jsonstring, MatchEvaluator);
      DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (T));
      MemoryStream ms = new MemoryStream (encodingutfgetbytes (jsonstring));
      T obj = (t) serreadobject (MS);
    return obj; ///&lt;summary&gt;///converts JSON serialization time from/date (1294499956278+0800) to string///&lt;/summary&gt; private Stati
      C String convertjsondatetodatestring (Match m) {string result = Stringempty;
      DateTime dt = new DateTime (1970,1,1);
      DT = Dtaddmilliseconds (Longparse (Mgroups[1]value));
      DT = Dttolocaltime ();
      result = Dttostring ("Yyyy-mm-dd hhmmss"); Return Result ///&lt;summary&gt;///Convert time string to JSON time///&lt;/summary&gt; private static string convertdatestringto
      Jsondate (Match m) {string result = Stringempty;
      DateTime dt = Datetimeparse (Mgroups[0]value);
      DT = Dttouniversaltime ();
      TimeSpan ts = dt-datetimeparse ("1970-01-01");
      result = StringFormat ("\\/date ({0}+0800) \\/", tstotalmilliseconds);
    return result; }
  }

Serialization Demo:

   Person p = new person ();
  P.name = "John";
  P.age =;
  P.lastlogintime = DateTime.Now; 
  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, using JavaScript processing

 function Changedateformat (jsondate) {
    jsondate = Jsondate.replace ("/date (", ""). Replace (")/", "");
    if (Jsondate.indexof ("+") > 0) {
      jsondate = jsondate.substring (0, Jsondate.indexof ("+"));
    }
    else if (Jsondate.indexof ("-") > 0) {
      jsondate = jsondate.substring (0, Jsondate.indexof ("-"));
    }
   
    var date = new Date (parseint (jsondate));
    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;
  }

Simple demo:

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

Results:

2011-1-8

Iv. JSON serialization and deserialization collection, dictionary, array processing

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

List<t> Serialization:

   list<person> list = new List<person> ()
  {
    new person () {name= ' john ', age=28},
    new person () {name= " Dick ", age=25}
  };
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:

   dictionary<string, string> dic = new dictionary<string, string> ();
  Dic. ADD ("Name", "John");
  Dic. ADD ("Age", "a");
  String jsonstring = Jsonhelper.jsonserializer < Dictionary<string, string>> (DIC);

Serialization Result:

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

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.