Serialization and deserialization of JSON in ASP.

Source: Internet
Author: User

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.

First, the JSON introduction:
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 ', ', ', ', ' ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', 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:


Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Runtime.Serialization.Json;
Using System.IO;
Using System.Text;

<summary>
JSON serialization and deserialization helper classes
</summary>
Publicclass Jsonhelper
{
<summary>
JSON serialization
</summary>
Publicstaticstring 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 ();
return jsonstring;
}

<summary>
JSON deserialization
</summary>
Publicstatic 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;
}
}

Serialization Demo:

Person P =new person ();
P.name = "Zhang San";
P.age = 28;
P.lastlogintime = DateTime.Now;
String jsonstring = Jsonhelper.jsonserializer<person> (p);
Run the row result:
{"Age": "Lastlogintime": "2011-01-09 01:00:56", "Name": "Zhang San"}
Deserialization Demo:
String json = "{\" age\ ": 28,\" lastlogintime\ ": \" 2011-01-0900: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

function Changedateformat (jsondate) {
Jsondate = Jsondate.replace ("/date (", ""). Replace (")/", "");
if (Jsondate.indexof ("+") >0) {
Jsondate = jsondate.substring (0, Jsondate.indexof ("+"));
}
ElseIf (Jsondate.indexof ("-") >0) {
Jsondate = jsondate.substring (0, Jsondate.indexof ("-"));
}

var date =new date (parseint (Jsondate, 10));
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

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:
list<person> List =new list<person> ()
{
New person () {name= ' Zhang San ', age=28},
New Person () {name= "John Doe", age=25}
};
String jsonstring = jsonhelper.jsonserializer<list<person>> (List);
  Serialization Result:
"[{\" age\ ": 28,\" name\ ": \" Zhang San \ "},{\" age\ ": 25,\" name\ ": \" john Doe \ "}]"
Dictionary cannot be used directly in JSON, The conversion of the Dictionary dictionary to JSON is not consistent with the original dictionary format, but instead takes the form of the dictionary key as the value of the name "key", with the value of dictionary named "value". such as:
Dictionary<string, string> dic =new dictionary<string, string> ();
Dic. ADD ("Name", "Zhang San");
DiC. ADD ("Age", "28");
String jsonstring = Jsonhelper.jsonserializer < Dictionary<string, string>> (DIC);
Serialization Result:
"[{\" 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

Serialization and deserialization of JSON in ASP.

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.