Handling of serialized custom objects formatted by datetime of the date type in Ajax JSON and custom type parameters

Source: Internet
Author: User

First, let's take a look at the processing of JSON serialization on the ASP. NET Ajax server side: (for details, see javascriptserializer. CS in the Ajax extension source code)

Internal static readonly long datetimemintimeticks = (New datetime (1970, 1, 1, 0, 0, 0, datetimekind. UTC). ticks;
Private Static void serializedatetime (datetime, stringbuilder SB ){

SB. append (@ "" // Date (");
SB. append (datetime. touniversaltime (). ticks-datetimemintimeticks)/10000 );
SB. append (@")//""");
}

At the earliest stage, Microsoft used the following method for serialization:

The Ajax JSON serialization program in ASP. Next encodes the datetime instance into a JSON string. In the pre-release period, ASP. NET Ajax uses the format"@ Ticks @Ticks indicates the number of milliseconds since January 1, January 1, 1970 in Universal Coordinated Time (UTC. The date and time in UTC (for example, November 29, 1989 4:55:30 AM) are encoded as"@ 62831853071 @". Although easy to understand, this format cannot distinguish the serialized date and time value from the value that looks like the serialized date but does not need to be deserialized. Therefore, the ASP. NET Ajax team modified the final version and solved this problem by adopting the "// Date (ticks) //" format.

The new style uses a small trick to reduce the possibility of misunderstanding. In JSON, the forward slash (/) character in the string can be backslash (/)
Escape (even if this is not strictly required ). The ASP. NET Ajax team used this to modify javascriptserializer and
Datetime instance is written as the string"// Date (ticks )//". The escape of the two forward slashes is superficial, but it is critical to javascriptserializer. According to the JSON rule,// Date (ticks )//"Technically equivalent to"/Date (ticks )/", But javascriptserializer will deserialize the former to datetime and deserialize the latter to string. Therefore,@ Ticks @"Format, the possibility of obfuscation is greatly reduced.

Note: This text is from the msdn article "JavaScript Object Notation (JSON) Introduction In JavaScript and. Net".

Here I want to add a trick. As you know, If <SCRIPT> and </SCRIPT> appear in the document, the step interpreter will parse the text, therefore, if you write the following code, an error will be prompted:

<SCRIPT>
Document. Write ("<SCRIPT> alert (1); </SCRIPT> ");
</SCRIPT>

Because the code "</SCRIPT>" appears in the middle, we can use:

<SCRIPT>
Document. Write ("<SCRIPT> alert (1); </scr" + "ERT> ");
</SCRIPT>

To avoid this error, we can also use "/" to escape:

<SCRIPT>
Document. Write ("<SCRIPT> alert (1); </SCRIPT> ");
</SCRIPT>

Bytes -----------------------------------------------------------------------------------------------------

Instance solution:

Class rssitem

[Property (notnull = true, column = "pubdate")]
Public Virtual datetime pubdate
{
Get {return _ pubdate ;}
Set {_ pubdate = value ;}
}

 

In WebService. CS

[Webmethod (description = "1234567")]
[Soapheader ("credentails", direction = soapheaderdirection. In)]
[Credentialextension]
// [Scriptmethod (responseformat = responseformat. JSON)]
Public dB. rssitem [] getarray ()
{
// This. verifycredential (this );
DB. rssitem [] objs = activerecordbase <dB. rssitem>. slicedfindall (0, 5 );
Foreach (rssitem OBJ in objs)
{
OBJ. tclass = new tclass ();
// Obj. tclass. Item = OBJ ;//
}
Return objs ;//
}

[Webmethod]
Public dB. rssitem getitem ()
{
DB. rssitem OBJ = getarray () [0]; // activerecordbase <dB. rssitem>. findfirst ();
Return OBJ ;//
}

[Webmethod]
[Soapheader ("credentails", direction = soapheaderdirection. In)]
[Credentialextension]
// [Generatescripttype (typeof (rssitem)]
// [Generatescripttype (typeof (tclass)]
Public dB. rssitem [] getarray2 (rssitem OBJ)
{
Return getarray ();
}

 

Client Js. aspx

<SCRIPT type = "text/JavaScript" src = "content/script/jquery-1.2.6.pack.js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "http://www.json.org/json2.js"> </SCRIPT>
<Script language = "JavaScript" type = "text/JavaScript">
// 1. the WebService request type is post, and the WebService URL is "[webserviceurl]/[webmethod]"
// 2. contenttype is declared as JSON
// 3. data must be transmitted in JSON string format
// 4. After the ype is set to JSON, the result is directly the returned JSON object.
VaR dd;
$ (Function ()
{
// No parameters are called.
$ ("# Btnhelloworld"). Click (function (){
$. Ajax ({
Type: "Post ",
Contenttype: "application/JSON ",
URL: "WebServices/webservice1.asmx/getitem ",
Data :"{}",
Datatype: 'json ',
Success: function (result ){
Dd = result. D;
Alert (result. D );
}
});

});
// Input a parameter
$ ("# Btnhello"). Click (function (){
VaR jsonstr = JSON. stringify (dd); // use json2.js to generate a JSON string


// Jsonstr = jsonstr. Replace (New Regexp ('(^ | [^ //]) // "///date //((-? [0-9] +) // "', 'G')," $ 1new date ($2) "); // set""// Date (ticks )//""To"New Date (ticks)"


// Jsonstr = jsonstr. Replace (New Regexp ('(^ | [^ //]) // "/date //((-? [0-9] +) // "', 'G')," $ 1new date ($2) "); // set""/Date (ticks )/"" To"New Date (ticks)"


Jsonstr = jsonstr. Replace (New Regexp ('(^ | [^ //]) // "/date //((-? [0-9] +) // "', 'G'),' $1/" // Date ($2) /// "'); // set""/Date (ticks )/""To""// Date (ticks )//""Or an error will occur !!!
// Alert (jsonstr );
$. Ajax ({
Type: "Post ",
Contenttype: "application/JSON ",
URL: "WebServices/webservice1.asmx/getarray2 ",
// Data: "{OBJ: 99 }",//
Data: "{OBJ:" + jsonstr + "}",//
Datatype: 'json ',
Success: function (result ){
Alert (result. D );
}
});
});

 

 

Solved the problem of customizing the rssitem type in the getarray2 parameter... OK !!!

 

 

 

 

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.